Python Docs
Python File Writing — Full Cheat Sheet
What is File Writing?
Writing files allows Python to store text, logs, results, and output permanently. You use the open() function with specific modes to write new content.
File Write Modes
- w — Write (overwrites existing file)
- a — Append (adds to end of file)
- x — Create a new file (error if file exists)
- t — Text mode (default)
- b — Binary mode
open(filename, "w")Basic Writing Example
Creates the file if missing, overwrites if it exists.
f = open("demofile.txt", "w")
f.write("Hello!")
f.close()Overwrite File Content
Using w always clears the existing file before writing.
f = open("demofile.txt", "w")
f.write("This text replaces the old content.")
f.close()Create a File (x Mode)
The x mode creates a file and throws an error if it already exists.
f = open("newfile.txt", "x")
f.write("New file created!")
f.close()Writing with with Statement
Using with is recommended because it automatically closes the file.
with open("notes.txt", "w") as f:
f.write("This is written using with-statement.")Write Multiple Lines
Use writelines() to write multiple strings.
lines = [
"Line 1" + "\n",
"Line 2" + "\n",
"Line 3" + "\n"
]
with open("demo.txt", "w") as f:
f.writelines(lines)Summary
- w: write new data, erase old data
- a: append data at end
- x: create new file, error if exists
- write(): writes single string
- writelines(): writes list of strings
- with: best practice for safe writing