Writing to a file in Python
Start your free 7-days trial now!
Writing to a file once
To write to an external file in Python:
file_name = "names.txt"with open(file_name, "w") as file: file.write("Alex\nBob\nCathy")
We end up with a text file called "names.txt"
with the following content:
AlexBobCathy
Writing to a file using the "w"
option results in overwrites
In our example, if you had a file called "names.txt"
already, then the contents of that file will be overwritten. To append to a file instead, use the "a"
option. This option is discussed below.
Writing to a file multiple times
Note that you could also write to a file multiple times:
file_name = "names.txt"with open(file_name, "w") as file: file.write("Alex\n") file.write("Bob\n") file.write("Cathy")
If you run this, we will end up with the exact same result:
AlexBobCathy
What's important here is that all your write
calls that are under the same with
do not overwrite each other.
Appending to a file
Instead of overwriting an existing file, you could append to it.
Suppose we have the following text file called names.txt
:
AlexBob
To append to this file:
file_name = "names.txt"with open(file_name, "a") as file: file.write("\nCathy") file.write("\nDave")
The resulting file is as follows:
AlexBobCathyDave