Python Guide #12: Writing to Files
In last guide, I showed you how to read content of the files with Python. In this turorial, I will teach you how to write data to files, either existing ones or to create new files and write data to them.
Python lets you choose file writing mode, it can be either write
or append
. Mode is passed as a parameter to open function.
# to write data to file, replacing all data within it
# or creating new file, if
# specified file does not exist
with open("path_to_file", "w") as f:
f.write(data)
# to append data to the end of
# the file
with open("path_to_file", "a") as f:
f.write(data)
Example
for i in range(10):
with open("file.txt", "w") as f:
f.write("Hello World!\n")
Execute programm above and open file.txt
to see its contents.
Now modify the program above, to instead of writing to file, it will append.
for i in range(10):
with open("file.txt", "a") as f:
f.write("Hello World!\n")
Open the file and see what happend. What happens if program above will be executed mulitple times?