Python File Read

In Python, you can read files using several methods, depending on how you want to handle the file’s contents. Below are common ways to read files in Python:

Reading the Entire File at Once

File.read() reads the entire file as a single string. This is useful for small files, but for large files, it’s better to read in chunks or lines.

Example:


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

Reading Line by Line (for Large Files)

This approach reads each line one at a time, which is efficient for larger files.


with open("filename.txt", "r") as file:
    for line in file:
        print(line.strip())  # `.strip()` removes extra whitespace

Reading All Lines as a List

file.readlines() returns a list of lines, where each line is an item in the list.


with open("filename.txt", "r") as file:
    lines = file.readlines()
    print(lines)  # Each line will be an item in the list

Reading in Chunks

For very large files, you can specify a chunk size (in bytes) to read portions of the file at a time.

Example:


with open("filename.txt", "r") as file:
    chunk_size = 1024  # For example, 1024 bytes
    while chunk := file.read(chunk_size):
        print(chunk)

This reads 1024 bytes at a time until the file is completely read.

Python File Read – Interview Questions

Q 1: How do you read a file in Python?
Ans: Using the read(), readline(), or readlines() methods.
Q 2: What does read() do?
Ans: It reads the entire content of the file as a string.
Q 3: What does readline() do?
Ans: It reads one line of the file at a time.
Q 4: What does readlines() return?
Ans: A list containing all lines of the file.
Q 5: Can you iterate over a file object?
Ans: Yes, using a for loop to read line by line.

Python File Read – Objective Questions (MCQs)

Q1. Which mode is used to read a file in Python?






Q2. Which method is used to write data to a file in Python?






Q3. What does the following code do?

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






Q4. Which method is used to read a single line from a file?






Q5. What is the purpose of the "a" mode in file handling?






Related Python File Read Topics