Himanshu SharmaSoftware engineer
Let’s talk

Python Tutorial · Lesson 46 of 70

Writing text files in Python

Create, overwrite and append to text files with open() modes, write lines correctly with newlines, and avoid losing data by choosing the right mode.

12 minErrors and filesUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonWrite and append text to files, choose between the w, a and x modes, and read the result back to check it.

After this lesson you will be able to save text from a program into a file, add new lines to an existing file without losing what is already there, and check what you wrote. This is how programs keep results after they finish.

Creating a file with mode "w"

open() takes a second argument, the mode. Mode "w" means write. It creates the file if it does not exist. If the file does exist, it is emptied the moment it is opened.

python
with open("report.txt", "w", encoding="utf-8") as f:
    f.write("Daily sales report\n")
    f.write("Pens: 40\n")
    f.write("Notebooks: 15\n")

with open("report.txt", encoding="utf-8") as f:
    print(f.read())
result
Daily sales report
Pens: 40
Notebooks: 15

Look at the \n at the end of each string. write() writes exactly what you give it and nothing more, so you must supply the line breaks. Here is what happens without them:

python
with open("run-together.txt", "w", encoding="utf-8") as f:
    f.write("Pens")
    f.write("Ink")

with open("run-together.txt", encoding="utf-8") as f:
    print(f.read())
result
PensInk

Overwriting is silent

Opening with "w" again wipes the earlier contents without any warning.

python
with open("report.txt", "w", encoding="utf-8") as f:
    f.write("Only this line is left\n")

with open("report.txt", encoding="utf-8") as f:
    print(f.read())
result
Only this line is left

When the old text matters, use a different mode or write to a new file name.

Adding to the end with mode "a"

Mode "a" is append. The file is created if needed, and new text goes after what is already there.

python
with open("log.txt", "a", encoding="utf-8") as f:
    f.write("Shop opened\n")

with open("log.txt", "a", encoding="utf-8") as f:
    f.write("First sale\n")

with open("log.txt", encoding="utf-8") as f:
    print(f.read())
result
Shop opened
First sale

Each run of a program would add more lines, which is exactly what you want for a log.

Modes at a glance

Mode Meaning If the file exists If it does not exist
"r" Read (the default) Opened for reading FileNotFoundError
"w" Write Emptied, then written Created
"a" Append New text goes at the end Created
"x" Create only FileExistsError Created

The "x" mode is a safety net. If you want to be sure you never destroy something, use it and handle the error:

python
try:
    with open("report.txt", "x", encoding="utf-8") as f:
        f.write("new report\n")
except FileExistsError:
    print("report.txt already exists, nothing written")
result
report.txt already exists, nothing written

Writing many lines

Loop and write one line at a time, or use print with the file argument, which adds the newline for you:

python
students = ["Asha", "Ben", "Chloe"]

with open("students.txt", "w", encoding="utf-8") as f:
    for number, name in enumerate(students, start=1):
        print(f"{number}. {name}", file=f)

with open("students.txt", encoding="utf-8") as f:
    print(f.read(), end="")
result
1. Asha
2. Ben
3. Chloe

writelines() writes a list of strings in one go, but it also adds no newlines, so include them yourself:

python
items = ["Pens", "Ink", "Paper"]

with open("items.txt", "w", encoding="utf-8") as f:
    f.writelines(item + "\n" for item in items)

with open("items.txt", encoding="utf-8") as f:
    print(f.read().splitlines())
result
['Pens', 'Ink', 'Paper']

Only strings can be written

In text mode write() accepts strings only. Numbers must be converted first:

python
with open("count.txt", "w", encoding="utf-8") as f:
    f.write(42)
result
TypeError: write() argument must be str, not int
python
with open("count.txt", "w", encoding="utf-8") as f:
    f.write(str(42))
    f.write(f"\n{40 + 2} again\n")

with open("count.txt", encoding="utf-8") as f:
    print(f.read(), end="")
result
42
42 again

Why with matters even more for writing

Python may keep written text in memory for a moment before it reaches the disk. Closing the file pushes it out. The with block closes the file for you, even if an error occurs halfway, so you keep what was written so far. If you ever open a file without with, you must call f.close() yourself.

Common mistakes

  • Opening with "w" when you meant "a". The earlier contents are gone. Pick the mode deliberately.
  • Forgetting \n. Everything lands on one line. Add the newline, or use print(..., file=f).
  • Writing a number directly. Convert it with str() or an f-string.
  • Reading a file you are still writing. Close it, or leave the with block, before opening it again for reading.
  • Opening a file for reading and writing it. Mode "r" cannot write. The error is io.UnsupportedOperation: not writable.

Exercise

Write a program that creates shopping.txt containing three items, one per line. Then append a fourth item, and finally read the file back and print how many lines it has.

Show one possible answer
python
with open("shopping.txt", "w", encoding="utf-8") as f:
    for item in ["bread", "milk", "rice"]:
        f.write(item + "\n")

with open("shopping.txt", "a", encoding="utf-8") as f:
    f.write("tea\n")

with open("shopping.txt", encoding="utf-8") as f:
    lines = f.read().splitlines()

print(lines)
print(len(lines), "lines")
result
['bread', 'milk', 'rice', 'tea']
4 lines

Next: CSV and JSON covers two common file formats for storing structured data. A video version of this topic is in the video course at /learn/python/.

Key points

  • open(name, 'w') creates the file or empties an existing one, 'a' adds to the end, and 'x' fails if the file already exists.
  • write() does not add a newline. You add \n yourself, or use print(..., file=f).
  • writelines() writes an iterable of strings but also does not add newlines.
  • write() only accepts strings, so convert numbers with str() or an f-string.
  • Using with closes the file and makes sure your data is saved.

Check yourself

1. What happens when you open an existing file with mode 'w'?
2. Which mode refuses to overwrite a file that already exists?
3. f.write('Pens') followed by f.write('Ink') produces what in the file?
4. What must you do before writing the number 12 with f.write()?