How to Write to a File in Python (Write & Append)
Learn how to write text to files in Python. Master the difference between write ("w") and append ("a") modes with safe context managers.
Explanation
Writing data to files is a fundamental task when building scripts, saving program states, creating logs, or exporting reports. Python simplifies file output using the built-in `open()` function, combined with specific file access modes that control how data is written to disk.
When writing files, the two most common modes are write mode (`"w"`) and append mode (`"a"`). Write mode overwrites the file entirely if it already exists, or creates a new one if it does not. Append mode preserves existing content and writes new data directly at the end of the file. Using the wrong mode can lead to accidental data loss, so choose carefully.
Similar to reading files, you should always use the `with open(...)` statement. This ensures the file buffer is flushed and the file handle is properly closed, saving system resources and preventing data corruption. For writing lists of strings, Python provides the `.writelines()` method, making bulk writes clean and efficient.
Step-by-Step Implementation
- 1
Use with open('filename', 'w') as file to overwrite or create a file.
- 2
Use with open('filename', 'a') as file to append text at the end of the file.
- 3
Call file.write('string') to write individual text segments to the file.
Code Example
This script demonstrates overwriting, appending, and viewing files in Python.
# 1. Overwrite a file (or create new) using "w"
with open("output.txt", "w") as file:
file.write("Hello World from Python!\n")
file.write("Writing file content is simple.\n")
# 2. Append new content to the file using "a"
with open("output.txt", "a") as file:
file.write("This line is appended.\n")
# 3. Reading the file back to verify contents
with open("output.txt", "r") as file:
print(file.read().strip())Hello World from Python!
Writing file content is simple.
This line is appended.Frequently Asked Questions
What happens if the directory of the file doesn't exist?
Python will raise a FileNotFoundError. You must create the directory first using the os.makedirs function before writing the file.
How do I write variables or numbers to a file?
The write() method only accepts string arguments. You must cast numbers using str(num) or format them using f-strings.
Related How-To Guides
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python File I/O
Learn how to read and write files in Python. Master open(), read(), write(), and context managers to handle file operations securely without resource leaks.
Python File Operations
Quick reference for reading and writing files in Python. Master open modes, context managers, and reading line-by-line.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.