Writing and Appending
Mode "w" writes and replaces the file, "a" appends to the end and "x" creates a new file and fails if it exists. Add "b" for binary files. Use print(..., file=f) or f.write() with your own newlines.
Example
import tempfile, os
path = os.path.join(tempfile.mkdtemp(), "log.txt")
with open(path, "w") as f:
f.write("one\n")
with open(path, "a") as f:
f.write("two\n")
with open(path) as f:
print(f.read())
print(os.path.exists(path))Result
one two True
Exercise
Add text to the end of a file.
open("log.txt", "")
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.