Using Text Files in Python
Overview In Python, it’s easy to read and write to text files Text files are made up of only ASCII text characters – Plain text Text files are used for permanently storing simple information Most operating systems come with basic tools for reading and writing to files Frequent operations – Open, Read, Write, Close When reading files you can read one line at a time, or read all lines in one read, into a list A line includes a newline character at the end ‘\n’ EOF means “End of File”. When reading files we read to the EOF Use Exception Handling to check for errors
Create and Write To A File # Create a new file. # The first argument is a string containing the filename # The second argument is another string containing a few # characters describing the way in which the file will be # used PATH = “c:\\my_file.txt” try : file = open(“workfile”, “w”) # open file.write(“Hello World”) # write file.close() # close except IOError as e : print(“Cannot open file “, PATH, “ for write”)
Reading From A File # Reading lines from a text file PATH = “read_it.txt” try : file = open(PATH, “r”) for line in file : print(line) # Close the file file.close() except IOError as e : print(“Can’t open and read file: “, PATH)
Selected Text File Modes “r” Read from a text file. If the file doesn’t exist, Python will raise an exception “w” Write to a text file. If the file exists, it contents are overwritten. If the file doesn’t exist, it is created “a” Append a text file. If the file exists, new data is appended to it. If the file doesn’t exist it is created
Some Text File Access Modes “r+” Read from and write to a text file. If it doesn’t exist, an exception is raised “w+” Write to and read from a text file. If the file exists, its contents are overwritten. If the file doesn’t exist, it is created “a+” Append and read from a text file. If the file exists, new data is appended to it. If the file doesn’t exist it is created
Example Programs http://jbryan2.create.stedwards.edu/cosc1323/textFiles.txt