Lesson 8
Making Objects the Main Star!
Chapter 9: Reading and writing files
Writing to files
As mentioned, Python opens a file in read mode ("r"
) by default.
To write to a file, remember to open your file in write mode ( "w"
). The file will either be created (if it does not exist) or cleared to be empty (if it exists). If Python complains that it cannot write to a file or that a file does not exist, you probably forgot to open it in write mode!
Use the .write()
method for writing strings to a file. Unlike print()
, the method does not automatically add a new line to the end of the string, so remember to add \n
yourself if needed.
As good practice, you should .close()
your file as soon as you are done with it (and especially if you are writing to the file)! This is mainly to conserve memory (every open file takes up memory) and to avoid corrupted files. You will not be able to read and/or write to the file once you have closed it. You will have to open the file again if you want to read/edit further.
Understand the code below. Then run it! You should get a new file named "assistant.txt"
in the same directory as your script, populated with the names of our capable teaching assistants!
assistants = ["Harry", "Joe", "Luca", "William"]
file = open("assistants.txt", "w")
file.write(f"{len(assistants)} great assistants:\n")
for assistant in assistants:
file.write(f"{assistant}\n")
file.close()
Use a with
statement
Instead of explicitly closing your files, Python recommends that you always open a file with a with
statement. This will always automatically close your file, e.g. when you exit the with
block or if your programs crashes while your file in open. So you do not even have to worry about forgetting to close the file!
assistants = ["Harry", "Joe", "Luca", "William"]
with open("assistants.txt", "w") as file:
file.write(f"{len(assistants)} great assistants:\n")
for assistant in assistants:
file.write(f"{assistant}\n")
This is called a context manager in Python. Here is yet another example of Python magic methods in action. The with
statement will invoke the file object’s __enter__()
magic method at the start, and will invoke the __exit()__
magic method at the end of the block (or when an error occurs inside the block). Of course, these methods are already implemented, so you do not even need to think about them!
You can also open multiple files in a single line with a with
statement.
assistants = ["Harry", "Joe", "Luca", "William"]
with open("data.txt", "r") as infile, open("out.txt") as outfile:
for line in infile:
outfile.write(line)
Other modes
There are also other modes you can use. For example,
"a"
(append) mode simply continues from the end of an existing file, rather than clearing the file."r+"
lets you read and write at the same time."w+"
will clear an existing file, and then lets you read and write at the same time.
Please check the official documentation for a complete list of modes, as well as other optional parameters for the open()
function.