You often need to write to a file to store data for later use. Python makes this really straightforward!
To use files with python, we only have to know one function to open the file, and a couple of flags to control how it’s opened.
def rememberer(thing):
file = open("database.txt", "a")
file.write(thing+"\n")
file.close()
if __name__ == '__main__':
rememberer(input("What should I remember? "))
open(“database.txt”)
Open to read from file — aka: open("database.txt", "r")
.
open(“database.txt”, “w”)
Open for a new write.
open(“database.txt”, “a”)
Open to append to the end of file.
write()
Write text to file.
close()
Close opened file.
Context Manager Pattern via with
The context manager pattern for dealing with files is:
def rememberer(thing):
with open("database.txt", "a") as file:
file.write(thing+"\n")
file.close()
if __name__ == '__main__':
rememberer(input("What should I remember? "))
Using with
, variables only exist for a certain time.
Since file
goes away once that with
is done, we won’t need file.close()
anymore.