Python Read Files


Reading files is one of the most common tasks in Python programming. By reading files, your program can access data stored externally, such as text, CSVs, or logs, and process it dynamically. Python provides built-in methods and functions to read files efficiently and safely.

This tutorial will cover opening files, reading content, reading line by line, handling large files, using context managers, and practical examples.

Opening Files for Reading

Python uses the open() function to access files. To read a file, you must specify the read mode ('r'):

file = open("example.txt", "r")
  • 'r' – read mode

  • 'rb' – read binary mode (for images or non-text files)

Always close the file after reading:

file.close()

Or use a context manager for automatic closing:

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

Reading Entire File Content

The read() method reads the entire content of the file as a single string:

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

You can also read a specific number of characters:

with open("example.txt", "r") as file:
    content = file.read(10)  # Reads first 10 characters
    print(content)

Reading One Line at a Time

The readline() method reads one line per call:

with open("example.txt", "r") as file:
    line1 = file.readline()
    line2 = file.readline()
    print(line1)
    print(line2)

This is useful for large files, where loading the entire file at once is inefficient.

Reading All Lines into a List

The readlines() method reads all lines and returns a list of strings:

with open("example.txt", "r") as file:
    lines = file.readlines()
    print(lines)

You can then iterate over this list:

for line in lines:
    print(line.strip())  # Remove extra newline characters

Iterating Through a File Object

A file object can be iterated directly using a for loop, which is memory-efficient:

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

This is ideal for processing large files line by line.

Checking File Existence

Before reading a file, it is safe to check if the file exists using the os module:

import os

if os.path.isfile("example.txt"):
    with open("example.txt", "r") as file:
        print(file.read())
else:
    print("File does not exist.")

This prevents errors and crashes when trying to read non-existent files.

Reading Large Files Efficiently

For very large files, reading line by line or using iterators prevents memory overload:

with open("large_file.txt", "r") as file:
    for line in file:
        process(line)  # Replace with actual processing logic

You can also use a while loop with readline():

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

Reading Binary Files

For non-text files like images or PDFs, use binary mode 'rb':

with open("image.jpg", "rb") as file:
    data = file.read()
    print(type(data))  # Output: <class 'bytes'>

Binary files return byte data, which can be processed or saved as needed.

Practical Examples

  1. Read a full text file:

with open("example.txt", "r") as file:
    content = file.read()
    print(content)
  1. Read first 20 characters only:

with open("example.txt", "r") as file:
    print(file.read(20))
  1. Read one line at a time:

with open("example.txt", "r") as file:
    print(file.readline())
  1. Read all lines into a list and print:

with open("example.txt", "r") as file:
    lines = file.readlines()
    for line in lines:
        print(line.strip())
  1. Iterate through a file efficiently:

with open("example.txt", "r") as file:
    for line in file:
        print(line.strip())
  1. Check if file exists before reading:

import os
if os.path.exists("example.txt"):
    with open("example.txt", "r") as file:
        print(file.read())
  1. Read a large file line by line:

with open("large_file.txt", "r") as file:
    for line in file:
        print(line.strip())
  1. Read a binary file:

with open("example.pdf", "rb") as file:
    data = file.read()
    print(len(data))  # Prints number of bytes
  1. Count number of lines in a file:

with open("example.txt", "r") as file:
    lines = file.readlines()
    print("Total lines:", len(lines))
  1. Print lines containing a specific word:

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

Summary of the Tutorial

Reading files in Python is essential for accessing stored data. The main techniques include:

  • read() – Read the entire file or a specific number of characters

  • readline() – Read one line at a time

  • readlines() – Read all lines into a list

  • Iterating through a file object – Efficient for large files

  • Binary mode – Reading images, PDFs, and other non-text files

  • Using context managers (with) – Automatic file closing and safer code

Mastering file reading allows you to process large datasets, logs, and text files efficiently, forming a foundation for real-world Python applications such as data analysis, automation, and report generation.


Practice Questions

Q1. Write a Python program to read and print all contents from sample.txt.

Q2. Write a Python program to read only the first 20 characters of a file using read(20).

Q3. Write a Python program to use readline() to read one line at a time from a file.

Q4. Write a Python program to loop through all lines in a file and print them using a for loop.

Q5. Write a Python program to read all lines using readlines() and print them as a list.

Q6. Write a Python program to strip newline characters when printing lines from a file.

Q7. Write a Python program to use with open() to safely read a file, ensuring it is properly closed.

Q8. Write a Python program to count the number of lines in a file using a loop.

Q9. Write a Python program to read a binary file (e.g., an image) using 'rb' mode and print its byte size.

Q10. Write a Python program to use read(0) on a file and explain the result (it returns an empty string because 0 characters were requested).


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top