Text files are collections of lines of text (strings) from Python's point of view. We frequently want to read a file, process that data, and then write the results in another file. We include a brief introduction to exception handling because it offers a clean way to prompt for a file name until you get a valid one.
Chapter 6: Files & Exceptions I
Text files are collections of lines of text (strings) from Python's point of view. Our primary interaction is to open a file for reading ("r") and then use for to iterate through the file one line at a time.
file_obj = open(filename_str,"r") for line in file_obj: suite-of-statementsWe process the data we read, open another file for writing ("w") and write data to that file. It is critically important to close a file after writing to it.
file_obj_out = open(filename2_str,"w") file_obj_out.write(some_string) file_obj_out.close()
Exceptions provide a new type of control that is useful for checking the validity of input, e.g. valid filename, valid floating-point number, etc. You try some code and if a particular error is raised, you handle it (in the except suite).
try: suite-of-statements except SomeError: suite-of-statements