Introduction

File handling lets a program save data to a file and read it back later, so the data is not lost when the program ends. In this lesson you will learn how to open a text file, read it in different ways, write and append to it, check whether it exists, and delete it, with output for every example.

Run these examples on your own computer. An online compiler may block or reset files, so file handling may not work there.

 

Open a file

The open() function takes the file name and a mode, and returns a file object.

Mode

Meaning

‘r’

Read (the default). The file must exist

‘w’

Write. Creates the file, or erases it if it exists

‘a’

Append. Adds to the end, and creates the file if needed

‘x’

Create. Fails if the file already exists

‘rb’ / ‘wb’

Read or write a binary file, such as an image

 

The with statement (the safe way)

A file must be closed after use. The with statement closes it automatically, even if an error happens. Always use it.

with open('notes.txt', 'w') as f:
    f.write('Hello\n')
    f.write('Python file handling\n')

This creates notes.txt with two lines. The \n at the end of each string adds a new line.

 

Read a file

read(): the whole file

with open('notes.txt', 'r') as f:
    print(f.read())

Output:

Hello
Python file handling

The output ends with an empty line, because the file ends with a new line and print() adds another.

You can also read a fixed number of characters:

with open('notes.txt') as f:
    print(f.read(5))
Hello

readline(): one line

with open('notes.txt') as f:
    print(f.readline(), end='')
Hello

Because each line already ends with a new line, end=” stops print() from adding a second one.

readlines(): all lines as a list

with open('notes.txt') as f:
    print(f.readlines())
['Hello\n', 'Python file handling\n']

Loop through the lines

The best way to read a large file is to loop over the file object. It reads one line at a time, so it uses little memory.

with open('notes.txt') as f:
    for line in f:
        print(line.strip())
Hello
Python file handling

strip() removes the new line at the end of each line.

 

Write to a file

Mode ‘w’ replaces the old content of the file. Use ‘a’ to add to the end.

with open('notes.txt', 'a') as f:
    f.write('Third line\n')

with open('notes.txt') as f:
    for line in f:
        print(line.strip())

Output:

Hello
Python file handling
Third line

writelines() writes a list of strings. It does not add new lines, so include \n yourself.

with open('nums.txt', 'w') as f:
    f.writelines(['1\n', '2\n', '3\n'])

with open('nums.txt') as f:
    print(sum(int(line) for line in f))
6

Count lines and words

with open('notes.txt') as f:
    text = f.read()

print(len(text.splitlines()))
print(len(text.split()))

Output:

3
6

The file has 3 lines and 6 words.

 

Check if a file exists, and delete it

import os

print(os.path.exists('notes.txt'))
os.remove('notes.txt')
print(os.path.exists('notes.txt'))

Output:

True
False

Handle a missing file

Opening a file that does not exist in read mode raises FileNotFoundError. Catch it so that the program does not crash.

try:
    with open('missing.txt') as f:
        print(f.read())
except FileNotFoundError:
    print('The file was not found')
The file was not found

See our lesson on exception handling for more.

 

Common mistakes

  • Using ‘w’ when you meant ‘a’. Mode ‘w’ erases the existing content.
  • Forgetting the new line character. write() does not add \n for you.
  • Not closing the file. Use with, so that the file is closed and the data is saved.
  • Wrong file path. If the file is not in the same folder as your program, give the full path.
  • Reading a file twice. After read(), the file position is at the end. Open the file again, or use seek(0).

 

Practice questions

  1. Write the numbers 1 to 10, one per line, to a file.
  2. Read the file back and print the sum of the numbers.
  3. Count how many lines of a text file contain the word ‘Python’.
  4. Copy the content of one file into another file.
  5. Append your name to the end of an existing file.

 

Summary

  • Use open(name, mode) with the with statement.
  • ‘r’ reads, ‘w’ writes (and erases), ‘a’ appends.
  • read(), readline(), readlines() and looping over the file read the content.
  • Use os.path.exists() and os.remove() to check and delete files, and catch FileNotFoundError.