Reading Files in Python

Reading files is a fundamental operation in Python programming. Python provides built-in functions and methods to open, read, and close files efficiently.

Key Concepts

10 Python Examples for Reading Files

Example 1: Reading entire file content

with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

Example 2: Reading file line by line using readline()

with open('example.txt', 'r') as file:
    line = file.readline()
    while line:
        print(line.strip())
        line = file.readline()

Example 3: Reading all lines into a list

with open('example.txt', 'r') as file:
    lines = file.readlines()
    for line in lines:
        print(line.strip())

Example 4: Using a for loop directly on the file object

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

Example 5: Reading a specific number of characters

with open('example.txt', 'r') as file:
    content = file.read(100)  # read first 100 characters
    print(content)

Example 6: Reading file in binary mode

with open('image.png', 'rb') as file:
    data = file.read()
    print(len(data), "bytes read")

Example 7: Reading large files line by line

with open('largefile.txt', 'r') as file:
    for line in file:
        process(line)  # replace with your processing logic

Example 8: Reading file with encoding specified

with open('example_utf8.txt', 'r', encoding='utf-8') as file:
    content = file.read()
    print(content)

Example 9: Reading and stripping whitespace

with open('example.txt', 'r') as file:
    lines = [line.strip() for line in file]
    print(lines)

Example 10: Handling file not found error

try:
    with open('missing.txt', 'r') as file:
        content = file.read()
except FileNotFoundError:
    print("File not found!")