Creating and writing a file
Programs also save data to files: results to keep for later, a report for a person to read, or data for another program to use. Writing uses the same open function as reading, with a second argument, the mode. The mode "w" opens the file for writing:
with open("greeting.txt", "w") as file:
file.write("Hello, file!\n")
file.write("This is the second line.\n")
with open("greeting.txt") as file:
print(file.read())
Hello, file!
This is the second line.open("greeting.txt", "w")creates the file in the program's folder.- The file handle's method
writewrites a string into the file. - The second
withblock opens the file for reading (with no mode,openreads) only to show what the program wrote. On this site, the tests of a task look at the files your program leaves in its folder.
write doesn't add line breaks
print ends each line for you, but write writes exactly the string it gets and nothing more. Line breaks are up to you: end each line with \n. Forget them, and the lines run together:
with open("numbers.txt", "w") as file:
file.write("one")
file.write("two\n")
file.write("three\n")
with open("numbers.txt") as file:
print(file.read())
onetwo
threeOnly strings
write takes exactly one string. Give it a number and Python stops:
points = 42
with open("points.txt", "w") as file:
file.write(points)
Traceback (most recent call last):
File "main.py", line 3, in <module>
file.write(points)
~~~~~~~~~~^^^^^^^^
TypeError: write() argument must be str, not intTurn the number into a string first. An f-string is the handiest way, and it adds the line break at the same time: file.write(f"{points}\n"). It works just as well for a line with several values, such as file.write(f"{name} scored {points}\n").
"w" starts from scratch
If a file with that name already exists, opening it with "w" empties it first. Everything that was in it is gone, without any warning:
with open("status.txt", "w") as file:
file.write("Version 1\n")
with open("status.txt", "w") as file:
file.write("Version 2\n")
with open("status.txt") as file:
print(file.read())
Version 2That's what you want when a program writes a fresh result every time it runs, but think twice about the name you give open with "w": a typo can wipe out the wrong file.