Lesson 45 of 70 – Writing Files
64%

Writing Files in Python

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.

Note: The w mode can replace existing file content, while the a mode adds new content to the end of the file.
What is File Writing?

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:

  • Creating a new text file
  • Writing content to a file
  • Appending content to a file
  • Writing multiple lines
  • Writing binary data
  • Updating an existing file
Writing with w Mode

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:

Hello Python
Writing Multiple Lines

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

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)
Output:
6

The word Python contains six characters.

Writing Numbers to a File

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.

Writing Multiple Data Values
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:

Name: Rahul
Age: 21
Using f-Strings While Writing

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.

Appending with a Mode

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.

Difference Between w and a
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

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.

Writing a List of Names
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.

Writing Lines Using a Loop
students = ["Amit", "Ravi", "Neha"]

with open("students.txt", "w") as file:

    for student in students:

        file.write(student + "\n")
File Content:
Amit
Ravi
Neha
Writing with UTF-8 Encoding

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.

Writing with a Newline
with open("data.txt", "w") as file:

    file.write("First Line\n")
    file.write("Second Line\n")
    file.write("Third Line\n")
File Content:
First Line
Second Line
Third Line
Writing a Simple Report
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")
File Content:
Student Report
----------------
Name: Rahul
Course: Python
Marks: 85
Appending Student Records

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")
Writing CSV-Style Data

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")
File Content:
Name,Age,Course
Amit,20,Python
Ravi,21,Java
Writing Binary Data

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.

Writing and Reading a File

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)
Output:
Hello Python
Using r+ Mode

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.

Using w+ Mode

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())
Output:
Python
Using a Mode

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.

Handling Writing Errors

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)
Best Practices for Writing Files
  • Use with open() for automatic file closing.
  • Choose the correct file mode.
  • Be careful with w mode because it replaces existing content.
  • Use a when new data should be added to existing content.
  • Specify an appropriate encoding for text files.
  • Use \n when separate lines are required.
  • Handle expected file-related exceptions.
  • Be careful when writing to important or existing files.
Key Points
  • 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.
  • Numbers can be converted to strings using str() before writing.
  • f-strings are useful for writing formatted data.
  • wb is used for writing binary data.
  • with open() automatically closes the file.
  • Always be careful when using modes that can overwrite existing data.

🧠 Quick Quiz

Question: Which file mode is commonly used to write data and replace existing file content?