Python File Write Tutorial: How to Write to Files in Python
Last updated 5 months, 1 week ago | 375 views 75 5

Python makes it easy to create and write to files using the built-in open()
function and file methods like .write()
and .writelines()
. Whether you're saving user input, logging events, or exporting data, writing to files is a key programming task.
In this article, you'll learn:
-
How to write to files in Python
-
The difference between write modes (
w
,a
,x
) -
Using
.write()
and.writelines()
-
Best practices with
with open(...)
-
A full working example
-
Tips and common mistakes
Opening a File for Writing
To write to a file, use the open()
function with the correct file mode:
file = open("filename.txt", "w") # 'w' for write
Common Write Modes
Mode | Description |
---|---|
'w' |
Write mode: overwrites the file if it exists |
'a' |
Append mode: adds to the end of the file |
'x' |
Create mode: creates a new file, errors if it exists |
Use
'w'
to start fresh,'a'
to keep existing content,'x'
to ensure a file is created only if it doesn't exist.
✍️ Writing with .write()
The .write()
method writes a single string to a file.
with open("example.txt", "w") as f:
f.write("Hello, world!\n")
f.write("Second line of text.\n")
Each call to .write()
adds the string exactly as given. To write new lines, include \n
.
Writing Multiple Lines with .writelines()
The .writelines()
method writes a list of strings to the file without adding newline characters automatically.
lines = ["First line\n", "Second line\n", "Third line\n"]
with open("example.txt", "w") as f:
f.writelines(lines)
❗ You must add
\n
manually to each string if you want line breaks.
✅ Best Practice: Use with
to Handle Files
The with
statement ensures the file is closed properly after writing, even if an error occurs.
Example:
with open("data.txt", "w") as f:
f.write("Using with statement is safer.")
This is cleaner and avoids the need for f.close()
.
Append to a File with 'a'
Mode
To keep existing data and add new content:
with open("log.txt", "a") as f:
f.write("New log entry.\n")
This adds to the end of the file without removing existing content.
Complete Example: Save a To-Do List
def save_todo_list(filename, tasks):
with open(filename, "w") as f:
for task in tasks:
f.write(task + "\n")
def add_task(filename, task):
with open(filename, "a") as f:
f.write(task + "\n")
def read_todo_list(filename):
with open(filename, "r") as f:
print("To-Do List:")
print(f.read())
# Usage
tasks = ["Buy groceries", "Finish Python tutorial", "Call Alice"]
save_todo_list("todo.txt", tasks)
add_task("todo.txt", "Walk the dog")
read_todo_list("todo.txt")
Output:
To-Do List:
Buy groceries
Finish Python tutorial
Call Alice
Walk the dog
⚠️ Common Mistakes and How to Avoid Them
Mistake | Problem | Solution |
---|---|---|
Not using with |
File may stay open | Always use with open(...) |
Forgetting \n |
All content on one line | Add \n to each line |
Using 'w' instead of 'a' |
File gets erased | Use 'a' for appending |
Writing non-string data | TypeError | Use str() or f-strings to convert data |
Pro Tips
-
Use
"utf-8"
encoding to support special characters:open("file.txt", "w", encoding="utf-8")
-
Use
.join()
and.writelines()
to write large lists efficiently -
Use
'x'
mode to prevent accidentally overwriting files -
Always test file-writing scripts on sample data before writing to important files
Summary
Task | Example |
---|---|
Write to new file | open("file.txt", "w") |
Append to file | open("file.txt", "a") |
Write a single string | f.write("text") |
Write multiple lines | f.writelines(["line1\n", "line2\n"]) |
Safely write and close file | with open(...) as f: |
Final Thoughts
Writing files in Python is easy and powerful. With the right file mode and structure, you can create logs, reports, user data files, and much more. Just remember to use with
, manage your newline characters, and choose the correct mode (w
, a
, or x
) depending on your goal.