Lesson 44 of 70 – Reading Files
63%

Reading Files in Python

Python provides several methods for reading data from a file. The most commonly used methods are read(), readline(), and readlines().

Note: Use with open() when possible. It automatically closes the file after the block finishes.
Opening a File for Reading

To read an existing text file, open it using r mode.

file = open("data.txt", "r")

print(file.read())

file.close()

The r mode means read mode.

Reading a File with with

The recommended approach is to use the with statement.

with open("data.txt", "r") as file:

    data = file.read()

    print(data)

The file is automatically closed when the with block ends.

read() Method

The read() method reads the contents of a file and returns them as a string for a text file.

Suppose data.txt contains:

Hello Python
Welcome to File Handling

Python code:

with open("data.txt", "r") as file:

    content = file.read()

print(content)
Output:
Hello Python
Welcome to File Handling
read() with Number of Characters

You can pass a number to read() to read up to that many characters from the current file position.

with open("data.txt", "r") as file:

    content = file.read(5)

print(content)

If the file starts with Hello Python, the output is:

Output:
Hello
Reading the Remaining Content

The file position moves forward as data is read.

with open("data.txt", "r") as file:

    print(file.read(5))
    print(file.read())

The first read(5) consumes up to five characters. The second read() reads from the current position to the end.

readline() Method

The readline() method reads one line at a time.

with open("data.txt", "r") as file:

    line = file.readline()

    print(line)

If the file contains:

Python
Java
JavaScript

The first call to readline() reads the first line.

Output:
Python
Reading Multiple Lines with readline()

Calling readline() repeatedly reads the next line each time.

with open("data.txt", "r") as file:

    line1 = file.readline()
    line2 = file.readline()

print(line1)
print(line2)
Output:
Python
Java
readlines() Method

The readlines() method reads all lines and returns them as a list.

with open("data.txt", "r") as file:

    lines = file.readlines()

print(lines)
Example Output:
['Python\n', 'Java\n', 'JavaScript\n']
Reading a File Using a for Loop

A file object can be iterated over directly.

with open("data.txt", "r") as file:

    for line in file:
        print(line)

This processes the file one line at a time.

Removing Extra Newline

Lines read from a text file often contain a newline character. The strip() method can remove surrounding whitespace.

with open("data.txt", "r") as file:

    for line in file:
        print(line.strip())

This is useful when you want to print each line without the extra newline or surrounding whitespace.

Reading with Encoding

When reading text files, you can specify the encoding explicitly.

with open(
    "data.txt",
    "r",
    encoding="utf-8"
) as file:

    content = file.read()

print(content)

UTF-8 is a widely used encoding for text.

Reading an Empty File

If a file has no more data to read, read() returns an empty string.

with open("data.txt", "r") as file:

    data = file.read()

    if data == "":
        print("File is empty")

    else:
        print(data)
Checking File Position with tell()

The tell() method returns the current position in the file.

with open("data.txt", "r") as file:

    print(file.tell())

    file.read(5)

    print(file.tell())

The exact position depends on the file content and text stream.

Moving the File Position with seek()

The seek() method changes the current file position.

with open("data.txt", "r") as file:

    file.read(5)

    file.seek(0)

    content = file.read()

    print(content)

Here, seek(0) moves the position back to the beginning.

Reading a Specific Line

One simple way to access a specific line is to read the lines into a list.

with open("data.txt", "r") as file:

    lines = file.readlines()

print(lines[1])

List indexing starts from 0, so lines[1] represents the second line.

Reading Lines into a List Without Newline
with open("data.txt", "r") as file:

    lines = [
        line.strip()
        for line in file
    ]

print(lines)
Example Output:
['Python', 'Java', 'JavaScript']
Reading Large Files

For large files, reading the entire file at once may use a lot of memory. Processing the file line by line is often more appropriate.

with open("largefile.txt", "r") as file:

    for line in file:
        process = line.strip()

        print(process)

This approach processes one line at a time.

Reading Binary Files

Binary files should be opened using a binary mode such as rb.

with open("image.jpg", "rb") as file:

    data = file.read()

print(len(data))

The result of reading binary data is a bytes object.

Handling FileNotFoundError

If the requested file does not exist, opening it in read mode raises FileNotFoundError.

try:

    with open("student.txt", "r") as file:
        data = file.read()

    print(data)

except FileNotFoundError:

    print("Student file not found")
Output if the file is missing:
Student file not found
Reading a Student File

Suppose student.txt contains:

Name: Rahul
Course: Python
Age: 21

Python code:

with open("student.txt", "r", encoding="utf-8") as file:

    for line in file:

        print(line.strip())
Output:
Name: Rahul
Course: Python
Age: 21
Reading and Counting Lines
count = 0

with open("data.txt", "r") as file:

    for line in file:

        count += 1

print("Total lines:", count)

The variable count keeps track of the number of lines read.

Reading and Counting Words
with open("data.txt", "r") as file:

    content = file.read()

words = content.split()

print("Total words:", len(words))

The split() method separates the text into words using whitespace by default.

Reading Data into a Variable
with open("message.txt", "r", encoding="utf-8") as file:

    message = file.read()

print("Message:", message)

The complete file content is stored in the message variable.

read(), readline() and readlines()
Method Purpose
read() Reads the file content or a specified number of characters.
readline() Reads one line at a time.
readlines() Reads lines and returns them as a list.
Key Points
  • Use open() to open a file.
  • Use r mode to read a file.
  • read() reads file content.
  • readline() reads one line at a time.
  • readlines() returns file lines as a list.
  • A file can be iterated over directly with a for loop.
  • strip() can remove surrounding whitespace from a line.
  • tell() returns the current file position.
  • seek() changes the file position.
  • Use encoding="utf-8" when appropriate for text files.
  • Use rb when reading binary files.
  • Use with open() to automatically close the file.

🧠 Quick Quiz

Question: Which method reads one line from a file?