Python provides several ways to write data into files. The most commonly
used methods are write() and writelines().
Python uses file modes such as w and a to control
how data is written.
w mode can replace existing file content, while
the a mode adds new content to the end of the file.
File writing means storing data in a file using a Python program. The data can be text, numbers converted to text, or other supported data representations.
Common writing operations include:
The w mode opens a file for writing.
If the file does not exist, Python creates it.
If the file already exists, its previous contents are replaced.
with open("data.txt", "w") as file:
file.write("Hello Python")
The file will contain:
The write() method can be called multiple times.
with open("data.txt", "w") as file:
file.write("Python\n")
file.write("Java\n")
file.write("JavaScript\n")
The \n character moves the next text to a new line.
The write() method writes a string to a file and returns
the number of characters written.
with open("data.txt", "w") as file:
count = file.write("Python")
print(count)
The word Python contains six characters.
Text files expect strings when using write().
Therefore, numbers normally need to be converted to strings.
age = 21
with open("data.txt", "w") as file:
file.write(str(age))
The number 21 is converted to the string "21"
before writing.
name = "Rahul"
age = 21
with open("student.txt", "w") as file:
file.write("Name: " + name + "\n")
file.write("Age: " + str(age))
The resulting file contains:
f-strings provide a convenient way to combine variables and text.
name = "Amit"
age = 20
with open("student.txt", "w") as file:
file.write(f"Name: {name}\n")
file.write(f"Age: {age}\n")
This produces readable text in the file.
The a mode appends new content to the end of a file.
with open("data.txt", "a") as file:
file.write("\nWelcome to Python")
Existing content remains and the new text is added at the end.
| w Mode | a Mode |
|---|---|
| Writes to a file. | Appends to a file. |
| Existing contents are replaced. | Existing contents are preserved. |
| Creates the file if it does not exist. | Creates the file if it does not exist. |
The writelines() method writes multiple strings to a file.
It does not automatically add newline characters between the strings.
lines = [
"Python\n",
"Java\n",
"JavaScript\n"
]
with open("languages.txt", "w") as file:
file.writelines(lines)
Each string contains \n so that it appears on a separate line.
students = [
"Amit\n",
"Ravi\n",
"Neha\n",
"Pooja\n"
]
with open("students.txt", "w") as file:
file.writelines(students)
The file will contain each student name on a separate line.
students = ["Amit", "Ravi", "Neha"]
with open("students.txt", "w") as file:
for student in students:
file.write(student + "\n")
When writing text containing different languages or special characters, specifying UTF-8 encoding is often a good practice.
message = "नमस्ते Python"
with open(
"message.txt",
"w",
encoding="utf-8"
) as file:
file.write(message)
UTF-8 supports a wide range of Unicode characters.
with open("data.txt", "w") as file:
file.write("First Line\n")
file.write("Second Line\n")
file.write("Third Line\n")
name = "Rahul"
course = "Python"
marks = 85
with open("report.txt", "w") as file:
file.write("Student Report\n")
file.write("----------------\n")
file.write(f"Name: {name}\n")
file.write(f"Course: {course}\n")
file.write(f"Marks: {marks}\n")
Append mode is useful when new records should be added without removing old records.
name = "Neha"
course = "Python"
with open("students.txt", "a") as file:
file.write(f"{name} - {course}\n")
Simple comma-separated text can be written manually, although the
csv module is preferable for robust CSV processing.
with open("students.csv", "w") as file:
file.write("Name,Age,Course\n")
file.write("Amit,20,Python\n")
file.write("Ravi,21,Java\n")
Binary data must be written using a binary mode such as wb.
The data supplied to write() must be bytes-like data.
data = b"Hello Python"
with open("data.bin", "wb") as file:
file.write(data)
The prefix b creates a bytes literal.
A file can be written first and then opened separately for reading.
with open("message.txt", "w") as file:
file.write("Hello Python")
with open("message.txt", "r") as file:
content = file.read()
print(content)
The r+ mode opens an existing file for both reading and writing.
The file must already exist.
with open("data.txt", "r+") as file:
content = file.read()
print(content)
file.write("\nNew text")
The exact position where new data is written depends on the current file position.
The w+ mode allows both reading and writing, but opening the
file in this mode truncates an existing file.
with open("data.txt", "w+") as file:
file.write("Python")
file.seek(0)
print(file.read())
The a+ mode allows reading and appending.
with open("data.txt", "a+") as file:
file.write("\nNew Line")
file.seek(0)
print(file.read())
After appending, seek(0) moves the position back to the
beginning before reading.
File operations can fail for reasons such as invalid paths or permission
problems. Exceptions can be handled using try and
except.
try:
with open("data.txt", "w") as file:
file.write("Hello Python")
except OSError as error:
print("File operation failed:", error)
with open() for automatic file closing.w mode because it replaces existing content.a when new data should be added to existing content.\n when separate lines are required.w mode is used for writing and can replace existing content.a mode appends data to the end of a file.write() writes a string to a file.writelines() writes multiple strings.\n is used to create a new line.str() before writing.wb is used for writing binary data.with open() automatically closes the file.Question: Which file mode is commonly used to write data and replace existing file content?