Go to Chapter 62 of A Smarter Way.
In Python, you don’t handle files directly. Instead you create a file handle, which opens the file either read-only or read-write. It is important to close the file when you are done!
The with syntax takes care of both opening and closing the file for you. This example opens the file for writing (“w”):
with open("some_filename.txt", "w") as file_handle:
or more conventionally:
with open("data.txt", "w") as f:
Yes, lots of people simply refer to the file as f, because the whole object is going to come and go quickly, in most cases. Don’t ask me how that’s PEP8 compliant.
If you are opening as read-only:
with open("data.txt", "r") as f:
And be especially careful when you want to append data -meaning you want to keep existing data:
with open("data.txt", "a") as f:
You’ll recognize the syntax so far: a statement followed by a colon character. We’re going to dive into an indent here, and do things with the file until we’re done:
with open("data.txt", "w") as f: #write to the file: f.write("Joe Jackson ID:123456") #read one line at a time: line = f.readline() print(line) # Read all lines in the file, as a list: lines = f.readlines() #and from here we're out of the with statement
Now go to this page, read it, and remember how to get back to it. 😉