How to Write Files in Python: A Beginner's Guide

# Introduction
Writing to files is an important Python skill. It allows you to save data forever instead of losing it when your system crashes. You can use file saving to store results, logs, reports, user input, settings, and structured data.
In this guide, you'll learn how to create text files, write multiple lines, add content, work with folders, and save data in CSV and JSON formats. You will also learn the most common file formats, including w, a, xagain rand when each is used.
Eventually, you will be able to write Python programs that save results, reports, logs, and structured data to files.
# Writing Your First Text File
The easiest way to write to a file is to use the built-in Python open() work.
I w mode means write mode. If the file does not exist, Python creates it. If the file already exists, Python overwrites its existing contents.
file = open("message.txt", "w")
file.write("Hello, this is my first file written with Python.")
file.close()
After running this code, Python creates a named file message.txt in the same folder as your notebook or text.
You can read the file again to check what is saved.
file = open("message.txt", "r")
content = file.read()
file.close()
print(content)
Output:
Hello, this is my first file written with Python.
# Using with open(): A Better Way
Although you can open and close files manually, the recommended method is to use it with open().
This automatically closes the file after you finish blocking the code. It's clean, safe, and often used in real Python projects.
with open("message.txt", "w") as file:
file.write("This file was written using with open().")
with open("message.txt", "r") as file:
content = file.read()
print(content)
Output:
This file was written using with open().
Using with open() It's a very good practice because you don't have to remember to close the file manually.
# Understanding File Modes
When you open a file, the mode tells Python what you want to do with it.
| Mode | Explanation |
|---|---|
w |
Write to a file. Creates a new file or overwrites an existing file. |
a |
Add to file. Adds content to the end without removing existing content. |
x |
Create a new file. It fails if the file already exists. |
r |
Read the file. It fails if the file does not exist. |
For writing files, the most common methods w again a. Use it w if you want to create a new file or replace existing content. Use it a if you want to add new content to the end of the file.
# Writing Multiple Lines
You can write multiple lines by adding a new line character n.
with open("notes.txt", "w") as file:
file.write("Line 1: Learn Pythonn")
file.write("Line 2: Practice file handlingn")
file.write("Line 3: Build small projectsn")
Read the file:
with open("notes.txt", "r") as file:
print(file.read())
Output:
Line 1: Learn Python
Line 2: Practice file handling
Line 3: Build small projects
You can also use writelines() writing a list of strings to a file.
tasks = [
"Write Python coden",
"Run the notebookn",
"Check the output filen"
]
with open("tasks.txt", "w") as file:
file.writelines(tasks)
Read the file:
with open("tasks.txt", "r") as file:
print(file.read())
Output:
Write Python code
Run the notebook
Check the output file
One important thing to remember is that writelines() does not automatically add line breaks. You need to install n on your own.
# Inserts into the file
Sometimes you don't want to change the existing content of a file. Instead, you may want to add new content at the end.
To do this, use add mode: a.
with open("journal.txt", "w") as file:
file.write("Day 1: I started learning Python file handling.n")
with open("journal.txt", "a") as file:
file.write("Day 2: I learned how to append text to a file.n")
Read the file:
with open("journal.txt", "r") as file:
print(file.read())
Output:
Day 1: I started learning Python file handling.
Day 2: I learned how to append text to a file.
Append mode is useful when working with logs, journals, reports, or any file where you want to keep adding new information.
# Creating Files Safely
If you want to create a new file but avoid overwriting the corner, use x mode.
This mode creates the file only if it does not already exist. If the file already exists, Python suggests a FileExistsError.
try:
with open("new_file.txt", "x") as file:
file.write("This file was created using x mode.")
print("File created successfully.")
except FileExistsError:
print("The file already exists, so Python did not overwrite it.")
If the file does not exist, you can see:
File created successfully.
If the file already exists, you can see:
The file already exists, so Python did not overwrite it.
This is useful if you want to protect existing files from being accidentally modified.
# Working with File Paths
By default, Python stores files in the same folder where your notebook or script is running.
If you want to save files inside a specific folder, you can use pathlib.
from pathlib import Path
output_folder = Path("output")
output_folder.mkdir(exist_ok=True)
file_path = output_folder / "summary.txt"
with open(file_path, "w") as file:
file.write("This file was saved inside the output folder.")
print(f"File saved to: {file_path}")
Output:
File saved to: output/summary.txt
Now read the file:
with open("output/summary.txt", "r") as file:
print(file.read())
Output:
This file was saved inside the output folder.
I mkdir(exist_ok=True) call creates the folder if it doesn't already exist. If the folder already exists, Python does not raise an error.
# Writing CSV Files
CSV files are useful for saving tabular data, such as rows and columns. They are usually opened in spreadsheet tools such as Excel or Google Sheets.
To write a CSV file in Python, use the csv module.
import csv
students = [
["Name", "Score"],
["Ayesha", 92],
["Bilal", 85],
["Sara", 88]
]
with open("students.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(students)
Read the CSV file:
with open("students.csv", "r") as file:
print(file.read())
Output:
Name,Score
Ayesha,92
Bilal,85
Sara,88
I newline="" Collision helps to avoid extra empty lines when writing CSV files, especially on Windows.
# Writes JSON Files
JSON is another common format for storing structured data. Commonly used for dictionaries, API responses, configuration files, and nested data.
To write JSON files in Python, use json module.
import json
profile = {
"name": "Ayesha",
"role": "Data Analyst",
"skills": ["Python", "SQL", "Excel"],
"active": True
}
with open("profile.json", "w") as file:
json.dump(profile, file, indent=4)
Read the JSON file:
with open("profile.json", "r") as file:
print(file.read())
Output:
{
"name": "Ayesha",
"role": "Data Analyst",
"skills": [
"Python",
"SQL",
"Excel"
],
"active": true
}
I indent=4 argument makes the JSON file easier to read.
# Common Beginner Mistakes
Here are some common mistakes beginners make when writing files in Python.
| It's a mistake | What's going on | How to Fix it |
|---|---|---|
| Forgot to close the file | Changes may not be saved properly | Use it with open() |
Using w instead of a |
Existing content is deleted | Use it a if you combine |
I forget n |
The text appears on one line | Add newline characters |
| It is writing to a folder that does not exist | Python raises an error | Create a folder first |
| Writing non-string data directly | Python may suggest a TypeError |
Convert values to strings or use CSV/JSON |
# Wrapping up
Writing files is one of the most useful skills for Python beginners. I still remember joining a programming competition in my second semester of engineering and I wasted almost an hour trying to figure out how to save the file. If I had known it was this easy, I would have won.
File saving helps you save logs, save program output, create reports, store user data, and even read and write simple databases using formats like JSON. The best part is that Python file management is natural, fast, and works out of the box.
For most jobs, use with open() because it closes the file automatically. Use it w writing or overwriting a file, a adding new content, as well x to safely create a new file without changing an existing one.
Abid Ali Awan (@1abidiawan) is a data science expert with a passion for building machine learning models. Currently, he specializes in content creation and technical blogging on machine learning and data science technologies. Abid holds a Master's degree in technology management and a bachelor's degree in telecommunication engineering. His idea is to create an AI product using a graph neural network for students with mental illness.



