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?
Q 2: What does read() do?
Q 3: What does readline() do?
Q 4: What does readlines() return?
Q 5: Can you iterate over a file object?
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?