PythonMastery
Python programs · Files · beginner

Read a file in Python

Read the whole contents of a text file into one string with read(), and handle the case where the file does not exist.

.read() reads the whole file into one string. This is the simplest way to read a file, and it is fine for small and medium files.

The program

python
# create a small file first, so there is something to read
with open("poem.txt", "w", encoding="utf-8") as f:
    f.write("Roses are red,\nViolets are blue,\nPython is fun,\nAnd so are you.\n")

with open("poem.txt", encoding="utf-8") as f:
    content = f.read()

print(content, end="")
print("Characters:", len(content))
output
Roses are red,
Violets are blue,
Python is fun,
And so are you.
Characters: 64

How it works

When the file is missing

If the file does not exist, open() raises FileNotFoundError. Catch it to show a clear message instead of a traceback:

python
filename = "missing.txt"

try:
    with open(filename, encoding="utf-8") as f:
        content = f.read()
except FileNotFoundError:
    print(f"Could not find {filename}")
output
Could not find missing.txt

For a very large file (for example a log file of several gigabytes), read() would load all of it into memory. Read it line by line instead.

Learn the idea: Files: Reading and Writing to Disk, File I/O, Pathlib, and Large Files