Introduction
Writing to files is a fundamental Python skill, crucial for anyone looking to delve deeper into programming. It allows you to save data permanently, thus preventing data loss when your program shuts down. This guide will teach you how to create text files, write multiple lines, append content, utilize folders, and save data in CSV and JSON formats. You’ll also gain an understanding of the most common file modes, such as w, a, x, and r, and learn when to use each. By the end, you’ll be able to write Python programs that can save results, reports, logs, and structured data to files, enhancing your programming capabilities.
Write Your First Text File
The simplest way to write to a file in Python is by using the built-in open() function. The w mode stands for write mode. If the file doesn’t exist, Python creates it. If it already exists, Python overwrites its content.
file = open("message.txt", "w")
file.write("Hello, this is my first file written with Python.")
file.close()
After executing this code, Python creates a file named message.txt in the same directory as your script or notebook. You can check the file’s content with the following code:
file = open("message.txt", "r")
content = file.read()
file.close()
print(content)
Output:
Hello, this is my first file written with Python.Use with open(): The Best Practice
Although you can manually open and close files, the recommended approach is to use with open(). This automatically closes the file once the code block is finished, making it cleaner and safer. It’s a common practice in real-world Python projects.
with open("message.txt", "w") as file:
file.write("This file was written using open().")
with open("message.txt", "r") as file:
content = file.read()
print(content)
Output:
This file was written using open().Using with open() is a best practice because you don’t need to remember to close the file manually, reducing the risk of errors in your code.
Understanding File Modes
When opening a file, the mode specifies what you intend to do with it.
| Mode | Description |
|---|---|
| w | Write to a file. Creates a new file or overwrites an existing file. |
| a | Append to a file. Adds content to the end without deleting existing content. |
| x | Create a new file. Fails if the file already exists. |
| r | Read a file. Fails if the file does not exist. |
For writing files, the most common modes are w and a. Use w when you want to create a new file or replace existing content, and a when you want to append new content to the end of a file.
Write Multiple Lines
You can write multiple lines to a file by adding the newline character n.
with open("notes.txt", "w") as file:
file.write("Line 1: Learn Pythonn")
file.write("Line 2: Practice file managementn")
file.write("Line 3: Create small projectsn")
Read the file:
with open("notes.txt", "r") as file:
print(file.read())
Output:
Line 1: Learn Python
Line 2: Practice file management
Line 3: Create small projects
You can also use writelines() to write 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
Remember, writelines() does not automatically add newlines, so you must include n yourself.
Adding to a File
Sometimes, you don’t want to overwrite existing content in a file; instead, you may want to append new content at the end. To do this, use the append 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 add 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 add text to a file.
Append mode is useful when working with logs, reports, or any other file where you want to continuously add new information.
Create Files Securely
If you want to create a new file but avoid overwriting an existing file, use the x mode. This mode only creates a file if it does not already exist. If the file exists, Python raises a FileExistsError.
try:
with open("new_file.txt", "x") as file:
file.write("This file was created using mode x.")
print("File created successfully.")
except FileExistsError:
print("The file already exists, so Python did not overwrite it.")
If the file does not exist, you will see:
File created successfully.If the file already exists, you will see:
The file already exists, so Python did not overwrite it.This approach is useful when you want to protect existing files from accidental overwriting.
Working with File Paths
By default, Python saves files in the same directory where your script or notebook is executed. If you want to save files to 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 in the output folder.")
print(f"File saved in: {file_path}")
Output:
File saved in: output/summary.txtNow read the file:
with open("output/summary.txt", "r") as file:
print(file.read())
Output:
This file was saved in the output folder.The mkdir(exist_ok=True) call creates the folder if it does not already exist. If the folder exists, Python does not raise an error.
Writing CSV Files
CSV files are useful for saving tabular data, such as rows and columns, and can be opened in spreadsheets like 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
The newline="" argument helps avoid extra blank lines when writing CSV files, particularly on Windows.
Writing JSON Files
JSON is another common format for saving structured data and is often used for dictionaries, API responses, configuration files, and embedded data. To write JSON files in Python, use the 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
}
The indent=4 argument makes the JSON file easier to read, enhancing its readability.
Common Beginner Mistakes
Here are some common mistakes beginners make while writing files in Python.
| Mistake | Consequence | Solution |
|---|---|---|
| Forgetting to close the file | Changes may not be saved correctly | Use with open() |
Using w instead of a | Existing content is deleted | Use a when appending |
| Forgetting newline characters | Text appears on a single line | Add newline characters |
| Writing to a non-existent folder | Python raises an error | Create the folder first |
| Writing non-string data directly | Python may raise a TypeError | Convert values to strings or use CSV/JSON |
Conclusion
Writing to files is a vital skill for Python beginners. It facilitates logging, saving program output, creating reports, persisting user data, and even interacting with simple databases using formats like JSON. Python’s file handling capabilities are native, fast, and versatile, making it an essential tool in any programmer’s toolkit. For most tasks, using with open() is advisable because it ensures files are automatically closed. Use w to write or overwrite a file, a to append new content, and x to create a new file safely without overwriting an existing one.
Abid Ali Awan (@1abidaliawan) is a certified professional data scientist passionate about building machine learning models. He focuses on content creation and writing technical blogs about machine learning and data science technologies. Abid holds a master’s degree in technology management and a bachelor’s degree in telecommunications engineering. His vision is to create an AI product using a graphical neural network to help students struggling with mental health issues.
For more in-depth guidance, visit the original article here.
“`

