Writing Files in Python
Learn how to create files, write data, append new content and save information using Python.
What is Writing to a File?
Writing to a file means storing data inside a file using a Python program.
Python provides different file modes such as
w, a and x
for writing and creating files.
Why Do We Write Data to Files?
Save Data
Store information for future use.
Create Reports
Generate text-based reports and results.
Store Logs
Save application or activity information.
Writing Files Diagram
The basic process of writing data to a file is:
Python Program
Creates or prepares data.
Open
Open file in writing mode.
Write
Use
write()
or
writelines().
Save
Data is stored in the file.
File
Written data is available for later use.
1. Write Mode - w
The w mode is used to write data into
a file.
If the file does not exist, Python creates it.
If the file already contains data, writing with
w can replace the existing content.
file = open("example.txt", "w")
file.write("Hello Python")
file.close()
After running the program, the file can contain:
Hello Python
w mode because existing
content can be replaced.
Writing with the with Statement
A common and convenient approach is to use
with.
with open("example.txt", "w") as file:
file.write("Hello Python")
file.write("\nWelcome to CIIT")
After the block finishes, Python handles the file resource automatically.
Writing Multiple Lines
We can use newline characters such as
\n to write multiple lines.
with open("students.txt", "w") as file:
file.write("Rahul\n")
file.write("Priya\n")
file.write("Amit\n")
file.write("Sneha\n")
The file content becomes:
Rahul
Priya
Amit
Sneha
2. Append Mode - a
The a mode is used to add new content
at the end of an existing file.
Existing content remains unchanged.
with open("students.txt", "a") as file:
file.write("Neha\n")
If the file already contains:
Rahul
Priya
Amit
Sneha
After appending, it can contain:
Rahul
Priya
Amit
Sneha
Neha
Write vs Append
w Mode
|
a Mode
|
|---|---|
| Writes new content. | Adds content to existing content. |
| Existing file content can be replaced. | Existing content is preserved. |
| Useful when creating or replacing file content. | Useful when adding new information. |
3. Create Mode - x
The x mode is used to create a new file.
If a file with the same name already exists, Python raises an error instead of replacing it.
file = open("newfile.txt", "x")
file.write("New file created")
file.close()
This mode is useful when you want to create a file only if it does not already exist.
Writing Multiple Lines with writelines()
The writelines() method can write a
sequence of strings to a file.
students = [
"Rahul\n",
"Priya\n",
"Amit\n"
]
with open("students.txt", "w") as file:
file.writelines(students)
The strings are written in the same order.
Writing List Data to a File
We can take data from a Python list and write each item into the file.
students = [
"Rahul",
"Priya",
"Amit"
]
with open("students.txt", "w") as file:
for student in students:
file.write(student + "\n")
The list data is stored one item per line.
Writing User Input to a File
We can get data from the user and store it in a file.
name = input("Enter your name: ")
with open("user.txt", "w") as file:
file.write(name)
print("Data saved successfully")
The entered name is stored inside
user.txt.
Append User Input
We can keep adding user entries without deleting previous data.
name = input("Enter your name: ")
with open("students.txt", "a") as file:
file.write(name + "\n")
print("Student added")
Every new name is added at the end of the file.
Output
Enter your name: Samadhan
Student added
Writing with Encoding
We can specify an encoding while opening a file.
with open(
"message.txt",
"w",
encoding="utf-8"
) as file:
file.write("Hello Python")
file.write("\nWelcome to Python")
UTF-8 is commonly used when working with Unicode text.
Using New Line Characters
The \n character is used to move
to the next line.
with open("example.txt", "w") as file:
file.write("Line 1\n")
file.write("Line 2\n")
file.write("Line 3\n")
File content:
Line 1
Line 2
Line 3
Example: Student Data 👨🏫📩
Let's store student information in a text file.
students = [
"Rahul - Python",
"Priya - Java",
"Amit - .NET",
"Sneha - MERN"
]
with open("students.txt", "w") as file:
for student in students:
file.write(student + "\n")
print("Student data saved")
The file can contain:
Rahul - Python
Priya - Java
Amit - .NET
Sneha - MERN
Handling File Writing Errors
File operations can sometimes fail because of permission issues, invalid paths or other problems.
We can use try and except
to handle errors.
try:
with open("example.txt", "w") as file:
file.write("Hello Python")
except OSError:
print("Unable to write to the file")
Important Writing Modes
| Mode | Use | Existing Content |
|---|---|---|
w
|
Write | Can be replaced |
a
|
Append | Preserved |
x
|
Create new file | Error if file exists |
Best Practices
Step 1: Choose the correct file mode.
↓
Step 2:
Use the with statement.
↓
Step 3: Write data carefully.
↓
Step 4: Use encoding when appropriate.
↓
Step 5: Handle possible file errors.
Common Mistakes
-
Using
wmode when existing content should be preserved. - Forgetting newline characters when writing multiple lines.
- Using an incorrect file path.
- Not handling possible file errors.
- Writing text using an inappropriate encoding.
Practice Programs
-
Create a file named
students.txtusingwmode. - Write five student names into the file.
-
Add another student using
amode. -
Create a file using
xmode. - Write a list of courses into a file.
-
Get a student's name using
input()and save it to a file. - Create a simple student report in a text file.
Summary
Python provides different modes for writing and
creating files. The w mode writes data
and can replace existing content, a
appends data to the end of a file, and x
creates a new file only if it does not already exist.
Methods such as write() and
writelines() are used to store data.
The with statement is a convenient way
to work with files safely.