Python Writing Files

In the last lesson, we learned about Python Reading Files. After learning how to read files, let us learn how to write files in Python. Writing means saving data to a file. That way, the data stays there even after our program ends.

In this tutorial, we will learn how to write to a file using write() and writelines(). We will also see how to format data and avoid common mistakes.

🧩 How to Open a File for Writing in Python

To write to a file, we open it in write mode. We use "w".

file = open("output.txt", "w")

Now file is a file object. We can use it to write.

But be careful. Write mode "w" erases the existing content. If the file already exists, all its data is gone. And a new empty file is created.

If the file does not exist, Python creates it.

πŸ’Ύ How to Write to a File with write()

The write() method writes a string to the file.

file = open("output.txt", "w")
file.write("Hello, world!\n")
file.write("This is a new line.\n")
file.close()

After running this, output.txt contains:

Hello, world!
This is a new line.

Notice the \n at the end of each line. That is a newline character. It moves the cursor to the next line. Without it, everything would be on one line.

πŸ”§ Using with Statement for Writing Files in Python

Just like reading, we should use the with statement for writing. It closes the file automatically.

with open("output.txt", "w") as file:
file.write("Hello, world!\n")
file.write("This is a new line.\n")

This is cleaner and safer. If an error happens, the file still gets closed.

πŸ’‘ How to Write Multiple Lines to a File in Python

We can write multiple lines by calling write() multiple times.

with open("fruits.txt", "w") as file:
file.write("apple\n")
file.write("banana\n")
file.write("orange\n")

After running this, fruits.txt contains:

apple
banana
orange

πŸ§ͺ How to Write a List of Lines with writelines()

If we have a list of strings, we can write them all at once using writelines().

lines = ["apple\n", "banana\n", "orange\n"]
with open("fruits.txt", "w") as file:
file.writelines(lines)

The result is the same.

But be careful. writelines() does not add newlines automatically. We have to include \n in each string ourselves.

lines = ["apple", "banana", "orange"]
with open("fruits.txt", "w") as file:
for line in lines:
file.write(line + "\n")

That is a safer way when our list does not have newlines.

πŸ“Œ How to Write Numbers to a File in Python

The write() method only accepts strings. If we try to write a number, we get an error.

with open("numbers.txt", "w") as file:
file.write(42)

Output

TypeError: write() argument must be str, not int

Fix: Convert the number to a string first.

with open("numbers.txt", "w") as file:
file.write(str(42))

Or use an f-string.

with open("numbers.txt", "w") as file:
file.write(f"{42}\n")

βš™οΈ Python Write to File Example

Let’s write a simple program that saves a user’s information to a file.

name = input("Enter your name: ")
age = input("Enter your age: ")
city = input("Enter your city: ")
with open("user_info.txt", "w") as file:
file.write(f"Name: {name}\n")
file.write(f"Age: {age}\n")
file.write(f"City: {city}\n")
print("Information saved!")

If the user enters Alex, 25, London, the file user_info.txt will contain:

Name: Alex
Age: 25
City: London

That is a simple way to save data.

πŸ” Another Example – Writing a Report to a File in Python

scores = [85, 92, 78, 95, 88]
with open("report.txt", "w") as file:
file.write("Score Report\n")
file.write("=" * 20 + "\n")
for i, score in enumerate(scores, 1):
file.write(f"Student {i}: {score}\n")
file.write("=" * 20 + "\n")
file.write(f"Average: {sum(scores) / len(scores):.1f}\n")
print("Report saved!")

The file report.txt will contain:

Score Report
====================
Student 1: 85
Student 2: 92
Student 3: 78
Student 4: 95
Student 5: 88
====================
Average: 87.6

That is a nice formatted report.

🧭 Common Mistakes When Writing Files in Python

❌ Mistake 1: Forgetting to close the file

file = open("output.txt", "w")
file.write("Hello")
# forgot to close

If we forget to close, the data might not be saved.

Fix: Use with or remember to call close().

🚫 Mistake 2: Using write mode when we meant append

with open("data.txt", "w") as file:
file.write("New data")

This erases the file. If we wanted to add to the end, we use "a".

πŸ›‘ Mistake 3: Trying to write a number

with open("numbers.txt", "w") as file:
file.write(42)

Output

TypeError: write() argument must be str, not int

Fix: Convert to string.

file.write(str(42))

Or use an f-string.

file.write(f"{42}")

🐞 Mistake 4: Forgetting the newline character

file.write("Hello")
file.write("World")

Output in file:

Output

HelloWorld

Fix: Add \n.

file.write("Hello\n")
file.write("World\n")

Next, we will learn Python Append Mode, so we can add new text to a file without erasing the old content.