← Back to Python Course | Chapter 9: File Handling | Lesson 2 of 6

Python Reading Files

Reading a file is like opening a book and looking at its pages. Python can read everything at once or one line at a time.
Syntax
python
with open("file_name", "r") as file:
    content = file.read()

Reading Entire File

f.read() loads an entire file's contents into one string in memory at once -- convenient for small files, but risky for very large ones since the whole thing has to fit in RAM before your program can even start processing it.

Example: Reading Entire File

python
with open("data.txt", "w") as f:
    f.write("all content at once")
with open("data.txt", "r") as f:
    print(f.read())  # loads the whole file into one string in memory

Reading Line by Line

Looping directly over a file object ('for line in f:') reads one line at a time without loading the whole file into memory first, making it the memory-efficient choice for processing logs or datasets that might be gigabytes in size.

Example: Reading Line by Line

python
with open("data.txt", "w") as f:
    f.write("line1\nline2\n")
with open("data.txt", "r") as f:
    for line in f:  # reads one line at a time, without loading the whole file first
        print(line.strip())

Reading All Lines into a List

f.readlines() reads the entire file and returns it as a list of strings, one per line -- unlike the line-by-line loop, this does load everything into memory, but gives you the convenience of indexing into a specific line number afterward.

Example: Reading All Lines into a List

python
with open("data.txt", "w") as f:
    f.write("a\nb\nc\n")
with open("data.txt", "r") as f:
    lines = f.readlines()  # loads every line into a list of strings
print(lines)

Safe Reading of Missing Files

Attempting to open a path that doesn't exist raises FileNotFoundError, so production code typically wraps file-opening in a try/except block to show a clear error message rather than letting the program crash with a raw traceback.

Example: Safe Reading of Missing Files

python
try:
    with open("missing.txt", "r") as f:
        print(f.read())
except FileNotFoundError:  # raised because the path doesn't exist
    print("File not found")

Stripping Newline Characters

Lines read from a file retain their trailing '\n' newline character, which is why you'll often see line.strip() or line.rstrip('\n') applied immediately after reading, to clean the text up before further processing.

Example: Stripping Newline Characters

python
with open("data.txt", "w") as f:
    f.write("hello\n")
with open("data.txt", "r") as f:
    line = f.readline()
print(repr(line))  # shows the trailing \n that was read from the file
print(repr(line.strip()))  # newline removed
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Calling read() on a huge file, which loads everything into memory, when looping over the file reads line by line.
  2. Forgetting that lines keep the trailing \n, so comparisons fail until you use line.strip().
  3. Reading from a file object a second time and getting an empty string, because the cursor is at the end; call seek(0) first.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.