Beginner   Chapter 99 · 25 min read · Module 8: File Handling

Writing Files

Learning objectives
  • After this chapter you can create a new text file with open() in "w" mode.
  • You can write text with write() and several lines with writelines().
  • You can explain that write mode erases the old content of an existing file.
  • You can send print() output into a file with the file argument.
  • You can write numbers and other values by converting them to strings first.

Reading files lets a program use saved data, but a program also needs to save its own results. Writing files is how you store a report, a list of scores, or the output of a long calculation so that it is still there after the program ends.

Python makes writing simple. You open a file in write mode, send text to it, and close it. The most important thing to learn is that write mode starts with an empty file every time. If the file already had content, that content is gone as soon as you open it.

In this chapter you will use the write mode, the write() and writelines() methods, and the file argument of print(). You will also learn why write() accepts only strings, and how to build lines with f-strings. Every example creates its files inside the program, so you can run them safely.

Opening a file for writing

To write, open the file with the mode "w". If the file does not exist, Python creates it. If the file already exists, Python truncates it, which means it removes everything inside and starts from zero. This happens at the moment you call open(), even if you never write anything afterwards.

Truncate: to cut a file down to zero length, removing all of its old content

As with reading, you should use the with statement. When the block ends, Python flushes the text that is waiting in memory to the disk and closes the file. If you forget to close a file you have written, some of the text may never reach the disk.

Example 1: write() and read it back
with open("hello.txt", "w") as f:
    f.write("Hello")
    f.write("World")
with open("hello.txt") as f:
    print(f.read())
HelloWorld

Notice the output: the two words are glued together. The method write() writes exactly the text you give it. It does not add a newline for you, unlike print(). If you want separate lines, you must put \n at the end of each string yourself.

Writing lines

Example 2: write lines with newlines
with open("lines.txt", "w") as f:
    f.write("first line\n")
    f.write("second line\n")
with open("lines.txt") as f:
    for line in f:
        print(line.strip())
first line second line

The method write() returns the number of characters it wrote. You will rarely need that number, but it can help to check your work. A related method, writelines(), takes any iterable of strings, such as a list, and writes them one after another. Be careful: writelines() also does not add newlines, so each string should already end with \n if you want separate lines.

Example 3: writelines() with a list
names = ["Asha", "Ben", "Chen"]
with open("names.txt", "w") as f:
    f.writelines(name + "\n" for name in names)
with open("names.txt") as f:
    print(f.read().splitlines())
['Asha', 'Ben', 'Chen']

Only strings can be written

A text file holds text, so write() accepts only strings. If you try to write a number, Python raises a TypeError. Convert the value first with str(), or build the line with an f-string, which is often the cleanest way. You can control the format inside the braces, for example two decimal places for a price.

Example 4: writing numbers with f-strings
scores = {"Asha": 90, "Ben": 85}
with open("scores.txt", "w") as f:
    for name, score in scores.items():
        f.write(f"{name},{score}\n")
    print(f.write(str(3.5)))
with open("scores.txt") as f:
    print(f.read())
3 Asha,90 Ben,85 3.5

Using print() to write

You can also write with print(). Give it the argument file=f and it writes to the file instead of the screen. The big advantage is that print() adds the newline for you and converts values to strings automatically. It also accepts sep and end like usual.

Example 5: print(file=...)
with open("p.txt", "w") as f:
    print("alpha", file=f)
    print(1, 2, 3, sep="-", file=f)
with open("p.txt") as f:
    print(f.read(), end="")
alpha 1-2-3

Write mode erases old content

This is the most common surprise for beginners. Opening an existing file with "w" deletes what was there. Run the next example and notice that the first text vanishes. If you want to keep the old content and add new text at the end, you need append mode, which is covered in the next chapter. If you want to create a file only when it does not exist yet, use the mode "x", which raises FileExistsError for an existing file.

Example 6: the old content is lost
with open("data.txt", "w") as f:
    f.write("version 1\n")
with open("data.txt", "w") as f:
    f.write("version 2\n")
with open("data.txt") as f:
    print(f.read().strip())
version 2
Example 7: exclusive creation with x
with open("once.txt", "x") as f:
    f.write("created\n")
try:
    with open("once.txt", "x") as f:
        f.write("again\n")
except FileExistsError:
    print("already exists")
already exists

Writing is usually buffered. This means Python collects small pieces of text in memory and sends them to the disk in larger chunks, because that is much faster than touching the disk for every call. When the file is closed, or when you call f.flush(), the waiting text is sent. This is another reason to use with: if your program stops in the middle without closing the file, some of the text may never be saved. A program that crashes inside a with block still closes the file properly.

Think about where the file goes. A name like out.txt is a relative path, so the file appears in the current working directory of the program. If you give a path with folders, such as reports/out.txt, the folder must already exist, because open() creates files but not folders. You can use os.makedirs or pathlib.Path.mkdir to create the folder first. Finally, remember the encoding: write with encoding="utf-8" when your text contains letters such as accents or symbols, and read it back with the same encoding.

Opening with "w" erases the file immediately. Double check the file name before you run a program that writes.

Python syntax

Syntax
with open("file.txt", "w", encoding="utf-8") as f:
    f.write("text\n")
Syntax
f.writelines(["a\n", "b\n"])
Syntax
print("text", file=f)

Real-world applications

  • Saving a report or the results of a calculation.
  • Creating a CSV style file with one record per line.
  • Writing a log or a small settings file.
  • Exporting data so another program can read it.

Common mistakes

Mistake: Opening an existing file with "w" and losing its old content.
Fix: Use "a" to add to the end, or write to a new file name.
Mistake: Forgetting the newline, so all text appears on one line.
Fix: End each string with \n, or use print(..., file=f).
Mistake: Passing a number to write() and getting TypeError.
Fix: Convert with str() or use an f-string.
Mistake: Expecting writelines() to add newlines.
Fix: Add \n to each string yourself.
Mistake: Not closing the file, so the text is not saved.
Fix: Always use the with statement.

Important tips

  • Use f-strings to build each line before writing it.
  • Read the file back in a test to check what was saved.
  • Use mode "x" when overwriting would be dangerous.

Key points summary

  • Mode "w" creates a file or erases an existing one.
  • write() needs a string and adds no newline.
  • writelines() writes strings from an iterable without newlines.
  • print(file=f) is a convenient way to write lines.
  • Mode "x" refuses to overwrite.

Exam and interview points

  • "w" truncates an existing file when opened.
  • write() accepts only str in text mode.
  • writelines() does not add line separators.
  • The "x" mode raises FileExistsError if the file exists.

Quick revision

  • "w" = create or erase.
  • write() adds no newline.
  • Convert numbers with str() or f-strings.
  • print(file=f) adds the newline.
  • "x" = create only if new.

Frequently asked questions

Does write mode create the file if it is missing?

Yes. Mode "w" creates a new empty file when the name does not exist.

How do I write a list of numbers?

Convert each number to a string, for example f.write("\n".join(str(n) for n in numbers) + "\n").

What does write() return?

It returns the number of characters written. Most programs ignore it.

Why is my file empty after running my program?

The file may not have been closed or flushed. Use with so Python closes it for you, and check that the program did not crash before the write.

Practise this chapter

18 practice questions Take the chapter quiz

Related chapters