Writing and Creating Files in Python
Writing and Creating Files
Reading files lets a program use existing data; writing files lets it save data — log entries, reports, exported records, user settings, and more. Python makes writing straightforward: open the file in the right mode and call write().
The mode you choose determines what happens to the file: whether new content is added to the end, whether existing content is replaced, or whether a brand-new file is created.
Write Modes at a Glance
| Mode | Name | If the File Exists | If the File Does Not Exist |
|---|---|---|---|
"a" | Append | Adds new data to the end; existing content is kept | Creates the file |
"w" | Write | Erases existing content, then writes from the beginning | Creates the file |
"x" | Exclusive create | Raises FileExistsError | Creates the file |
The write() Method
write() writes a string to the file and returns the number of characters written.
with open("demo.txt", "w") as file:
count = file.write("abc")
print(count)
Expected output:
3
Two important details about write():
- It accepts only strings in text mode. To write a number, convert it first:
file.write(str(42)). - It does not add a newline automatically (unlike
print()). Include"\n"wherever you want a line break.
with open("lines.txt", "w") as file:
file.write("First line\n")
file.write("Second line\n")
Without the \n characters, both pieces of text would end up on the same line: First lineSecond line.
Writing to an Existing File
Appending Content With "a"
Append mode adds new data to the end of the file without removing anything.
Assume log.txt already contains:
Server started.
with open("log.txt", "a") as file:
file.write("\nNew entry added successfully.")
The \n at the start moves the new entry onto its own line, because the existing content does not end with a newline.
Verifying the Updated Content
with open("log.txt", "r") as file:
print(file.read())
Expected output:
Server started.
New entry added successfully.
The original line is still there, and the new entry has been added after it. Append mode is ideal for logs, histories, and any file that grows over time.
Overwriting Content With "w"
Write mode replaces the entire content of the file.
with open("log.txt", "w") as file:
file.write("This file has been reset.")
Reading the File After Overwriting
with open("log.txt", "r") as file:
print(file.read())
Expected output:
This file has been reset.
Both earlier lines are gone.
Important: Opening a file in
"w"mode erases all of its content immediately — at the momentopen()is called, even before anything is written. If the program then fails before writing, the file is left empty. Use"w"only when you intend to replace the file completely.
Writing Multiple Lines
Using a Loop
tasks = ["Write report", "Email team", "Review code"]
with open("tasks.txt", "w", encoding="utf-8") as file:
for task in tasks:
file.write(task + "\n")
with open("tasks.txt", "r", encoding="utf-8") as file:
print(file.read())
Expected output:
Write report
Email team
Review code
Each task is written followed by a newline, so each appears on its own line.
Using writelines()
writelines() writes every string from a list (or other iterable). Like write(), it does not add newlines, so include them in the strings:
lines = ["Line one\n", "Line two\n", "Line three\n"]
with open("notes.txt", "w", encoding="utf-8") as file:
file.writelines(lines)
The file now contains three lines.
Creating New Files
Python can create files as part of opening them. The behavior depends on the mode:
| Mode | Creates a New File? | If the File Already Exists |
|---|---|---|
"x" | Yes | Raises FileExistsError |
"a" | Yes, if it does not exist | Opens it for appending |
"w" | Yes, if it does not exist | Erases it |
Example: Creating a New File With "x"
new_file = open("report.txt", "x")
new_file.close()
This creates an empty file named report.txt. Using with is cleaner and also lets you write the first content immediately:
with open("report.txt", "x", encoding="utf-8") as file:
file.write("Monthly Report\n")
Why Use "x" Mode?
"x" mode guarantees that an existing file is never overwritten by accident. If the file already exists, Python raises an error instead:
with open("report.txt", "x") as file:
file.write("New content")
Output:
FileExistsError: [Errno 17] File exists: 'report.txt'
Handle this case with try and except:
try:
with open("report.txt", "x") as file:
file.write("Monthly Report\n")
print("Report created.")
except FileExistsError:
print("Report already exists. Nothing was changed.")
Expected output (when the file already exists):
Report already exists. Nothing was changed.
Practical Example: A Simple Activity Logger
This function adds a timestamped entry to a log file each time it is called:
from datetime import datetime
def log_activity(message):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open("activity.log", "a", encoding="utf-8") as file:
file.write(f"[{timestamp}] {message}\n")
log_activity("User logged in")
log_activity("Report downloaded")
with open("activity.log", "r", encoding="utf-8") as file:
print(file.read())
Example output (your timestamps will differ):
[2026-10-01 14:35:12] User logged in
[2026-10-01 14:35:12] Report downloaded
Why append mode is correct here:
- The first call creates
activity.logif it does not exist. - Every later call adds a new line to the end, keeping all earlier entries.
- Using
"w"instead would leave only the most recent entry.
Choosing the Right Mode
| Goal | Mode |
|---|---|
| Add entries to a log or history | "a" |
| Save a fresh copy of data, replacing the old version | "w" |
| Create a file only if it does not already exist | "x" |
| Read an existing file | "r" |
Common Mistakes
| Mistake | Problem |
|---|---|
Using "w" instead of "a" | All existing content is lost |
Forgetting "\n" between writes | Text runs together on one line |
| Writing a number directly | TypeError: write() argument must be str, not int |
Writing in "r" mode | io.UnsupportedOperation: not writable |
Not closing the file (without with) | Written data may not be saved to disk |
Using "x" without handling FileExistsError | The program crashes if the file already exists |
Related Concepts
- Python File Handling — file modes and the
open()function - Python Opening Files — reading back the data you wrote
- Python Deleting Files — removing files you no longer need
- Python JSON — saving structured data with
json.dump()