CMPT 120 Lecture 23: Part 6: Using Files

26 views2 pages
meghan78 and 39786 others unlocked
CMPT 120 Full Course Notes
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.

Get access

Grade+
$40 USD/m
Billed monthly
Grade+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
10 Verified Answers
Class+
$30 USD/m
Billed monthly
Class+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
7 Verified Answers

Related Documents