CMPT 120 Lecture 23: Part 6: Using Files
meghan78 and 39786 others unlocked
29
CMPT 120 Full Course Notes
Verified Note
29 documents
Document Summary
To free up any system resources taken up by the open file. After calling close( ), we cannot use the file object anymore (in our python program). We saw that if the file does not exists, python interpreter produces and prints an error. Filenotfounderror: [errno 2] no such file or directory: "filedoesnotexist. txt" We can write guardian code against this and other errors called exceptions . Using the try statement (often called try block ). filedoesnotexist = "filedoesnotexist. txt" try: fin = open(filedoesnotexist) for line in fin: print(line) # and other processing fin. close() except: print("\n%s not found" %filedoesnotexist) Appending to a non-existing file? filetoappendtodoesnotexist = "filetoappendtodoesnotexist. txt" # what happen when i append to a non-existing file? fout = open(filetoappendtodoesnotexist, "a") fout. write("banana") fout. close( ) Dictionary: is another object in python that stores a collection of data. We use { } to define data in a dictionary. Each element in a dictionary consists of a key and a value.