Files & Error Handling

Reading Files

Python makes it easy to read text files.

Basic File Reading

# Open and read entire file
file = open("data.txt", "r")
content = file.read()
print(content)
file.close()

The with Statement (Recommended)

Automatically closes the file:

with open("data.txt", "r") as file:
    content = file.read()
    print(content)
# File automatically closed here

Reading Methods

with open("data.txt") as file:
    # Read all at once
    all_text = file.read()
    
    # Read line by line
    for line in file:
        print(line.strip())
    
    # Read all lines into a list
    lines = file.readlines()
python
Loading...
Output
Run execution to see output...