Python – reading and writing files.?? ???two ways to open a file open and file ??? How to write to...

20
Python – reading and writing files

Transcript of Python – reading and writing files.?? ???two ways to open a file open and file ??? How to write to...

Page 1: Python – reading and writing files.?? ???two ways to open a file open and file ??? How to write to relative and absolute paths?

Python – reading and writing files

Page 2: Python – reading and writing files.?? ???two ways to open a file open and file ??? How to write to relative and absolute paths?

???

• ???two ways to open a file open and file• ??? How to write to relative and absolute

paths?

Page 3: Python – reading and writing files.?? ???two ways to open a file open and file ??? How to write to relative and absolute paths?

To Write a file

• #written to C:\Users\jrw\workspace\Python1

• file = open("newfile.txt", "w")• file.write("Hello World \n")• file.close()

Page 4: Python – reading and writing files.?? ???two ways to open a file open and file ??? How to write to relative and absolute paths?

• #written to C:\Users\jrw\workspace\Python1

• file = open("newfile2.txt", "w")• file.write("Hello")• file.write("World")• file.close()• #writes HelloWorld• Note: you need to include “\n” for newline.

Page 5: Python – reading and writing files.?? ???two ways to open a file open and file ??? How to write to relative and absolute paths?

“””triple quotes”””

• file = open("newfile3.txt", "w")• file.write("""• Hello• Again""")• file.close()• #will write the following• Hello• Again

Page 6: Python – reading and writing files.?? ???two ways to open a file open and file ??? How to write to relative and absolute paths?

What does this write?

• #written to C:\Users\jrw\workspace\Python1

• file = open("newfile4.txt", "w")• file.write("Hello")• file.close()• file = open("newfile4.txt", "w")• file.write("Again")• file.close()

Page 7: Python – reading and writing files.?? ???two ways to open a file open and file ??? How to write to relative and absolute paths?

What does this write?

• #written to C:\Users\jrw\workspace\Python1

• file = open("newfile5.txt", "w")

• file.write("Hello")• file.write("Again")• file.close()

Page 8: Python – reading and writing files.?? ???two ways to open a file open and file ??? How to write to relative and absolute paths?

Printing to a file

• file = open("newfile5.txt", "w")

• print >> file, "START OF FILE"• print >> file, "END OF FILE"• del file• #this will print directly to a file• #del file deletes the file object and allows

contents to be written to file.

Page 9: Python – reading and writing files.?? ???two ways to open a file open and file ??? How to write to relative and absolute paths?

Appending a File

• with open("test.txt", "a") as myfile:

• myfile.write("appended text")

Page 10: Python – reading and writing files.?? ???two ways to open a file open and file ??? How to write to relative and absolute paths?

Reading a line of a File

• input1 = file("newfile5.txt", "r")

• print input1.readline()• print input1.readline()• #this will also read the “\n” at the end of line

Page 11: Python – reading and writing files.?? ???two ways to open a file open and file ??? How to write to relative and absolute paths?

Read a file

• input1 = file("newfile5.txt", "r")

• print input1.read()• #this will read the remainder of a file

Page 12: Python – reading and writing files.?? ???two ways to open a file open and file ??? How to write to relative and absolute paths?

Reads a file into a list

• with open("newfile5.txt") as f:• contents = f.readlines()• • for content in contents:• print content• ??? Read a file into an array. • ??? Number of lines in a file

Page 13: Python – reading and writing files.?? ???two ways to open a file open and file ??? How to write to relative and absolute paths?

Iterate through a file (line by line)

• input1 = file("newfile5.txt", "r")

• for line in input1.readlines():• print str(len(line)) + " " + line

• #adds the length of a line to the start of each line

Page 14: Python – reading and writing files.?? ???two ways to open a file open and file ??? How to write to relative and absolute paths?

File Exceptions• A file or directory (path) does not exist.• You do not have read/write permissions• Disk error• try:• fh = open("output/testfile1.txt", "w")• fh.write("This is my test file for exception handling!!")

• except IOError:• print "Error: can\'t find file or read data"• else:• print "Written content in the file successfully"

• fh.close()

Page 15: Python – reading and writing files.?? ???two ways to open a file open and file ??? How to write to relative and absolute paths?

Enter A Number

• while True:• try:• x = int(raw_input("Please enter a number: "))

• break• except ValueError:• print "Oops! That was no valid number. Try again"

• • print "you entered" + str(x)

Page 16: Python – reading and writing files.?? ???two ways to open a file open and file ??? How to write to relative and absolute paths?

Path - join

• import os.path• filePath = os.path.join("output", "file1.txt")

• #output\file1.txt• fh = open(filePath , "w")• fh.write("in file output\file1.txt on Windows machine")

Page 17: Python – reading and writing files.?? ???two ways to open a file open and file ??? How to write to relative and absolute paths?

Path - split

• import os.path• filePath = os.path.split("output/file1.txt")

• (pathName, fileName) = filePath• print pathName # output• print fileName # file1.txt

Page 18: Python – reading and writing files.?? ???two ways to open a file open and file ??? How to write to relative and absolute paths?

Path – split recursively

• import os.path• def split_fully(path):• parent_path, name = os.path.split(path)

• if name == "":• return (parent_path, )• else:• return split_fully(parent_path) + (name, )

• split_fully("dir1/dir2/file1.txt") • #('', 'dir1', 'dir2', 'file1.txt')

Page 19: Python – reading and writing files.?? ???two ways to open a file open and file ??? How to write to relative and absolute paths?

Splitting file extensions

• import os.path• print os.path.splitext("file.txt")

• #('file', '.txt')

Page 20: Python – reading and writing files.?? ???two ways to open a file open and file ??? How to write to relative and absolute paths?

If a path exists

• print os.path.exists("C:\Users\jrw\file.txt")

• #returns true or false