Chapter 13

Reading and Writing Files

Learn to open, read, and write text files safely using the with statement.

Reading and Writing Files

Programs often need to store information that outlives a single run. Python lets you read from and write to text files using the built-in open() function, which takes a filename and a mode.

File Modes

  • The read mode, written as the letter r, opens a file for reading.
  • The write mode, written as the letter w, creates or overwrites a file.
  • The append mode, written as the letter a, adds new text to the end without erasing what is there.

The with Statement

The best way to open a file is the with statement. It closes the file for you automatically when the block ends, even if an error happens. This avoids forgetting to close the file.

with open('notes.txt', 'w') as f:
    f.write('Hello')

with open('notes.txt', 'r') as f:
    text = f.read()
    print(text)   # Hello

Ways to Read

The read() method returns the whole file as one string. The readlines() method returns a list where each item is one line. You can also loop over the file object line by line.

with open('data.txt', 'r') as f:
    for line in f:
        print(line.strip())

Writing Text

The write() method adds text and returns the number of characters written. Note that write() does not add a new line by itself, so you must include line breaks yourself when you want them.

with open('log.txt', 'a') as f:
    f.write('New entry')

If you try to open a file that does not exist in read mode, Python raises a FileNotFoundError.

A Common Pattern

A very typical task is to read numbers or words from a file, process them, and write a result back to a new file. Reading line by line inside a with block keeps memory use low even for large files, because you never load the whole file at once.

total = 0
with open('scores.txt', 'r') as f:
    for line in f:
        total = total + int(line.strip())
print(total)

Always prefer the with statement over opening and closing files by hand. It is shorter, it protects against forgotten closes, and it still releases the file even if an error interrupts your code partway through.

Remember

  • open() takes a filename and a mode such as r, w, or a.
  • Mode w overwrites; mode a appends to the end.
  • The with statement closes the file automatically.
  • read() returns all text; readlines() returns a list of lines.
  • Opening a missing file for reading raises FileNotFoundError.

Stuck on this topic? A verified JomKelas tutor can walk you through it.

Find a verified tutor