Back to Study Material Python

Read Files

Reading files is one of the most common operations in Python programming. Whether you are loading a configuration file, parsing a CSV, or processing logs, ...

Read Files

Reading Files in Python: Methods and Best Practices

Reading files is one of the most common operations in Python programming. Whether you are loading a configuration file, parsing a CSV, or processing logs, you need to know the different ways Python lets you read file content and when each approach is appropriate.

Python's file object provides three main reading methods. The read() method reads the entire file and returns it as a single string. This is convenient for small files but can exhaust memory if the file is very large. The readline() method reads one line at a time, returning an empty string when the file is exhausted. The readlines() method reads all lines at once and returns them as a list.

with open("sample.txt", "r", encoding="utf-8") as f: # Read all at once content = f.read()

with open("sample.txt", "r", encoding="utf-8") as f: # Read line by line with a loop for line in f: print(line.rstrip())

with open("sample.txt", "r", encoding="utf-8") as f: # Get all lines as a list lines = f.readlines()

The most memory-efficient way to read a large file is to iterate over the file object directly in a for loop. Python reads the file buffer by buffer internally, so you never load more than a small chunk at a time. This approach is strongly preferred when working with log files, data dumps, or any file that could be hundreds of megabytes in size.

After calling read(), the file pointer is at the end of the file. If you try to read again without seeking back, you will get an empty string. You can reset the position using f.seek(0) to move back to the beginning, or f.seek(n) to move to a specific byte offset.

To read binary files such as images, audio, or compiled code, open the file with the "rb" mode. The content will be returned as bytes instead of a string, and you should not specify an encoding.

with open("image.png", "rb") as f: data = f.read() print(f"File size: {len(data)} bytes")

Exam tip: Know the distinction between read(), readline(), and readlines(). Also remember that iterating over a file object with a for loop is equivalent to calling readline() repeatedly but is more Pythonic and memory-efficient. The strip() and rstrip() methods are commonly used to remove the newline characters at the end of each line.