Interview question
What is the difference between read(), readline(), and readlines()? read(), readline(), और readlines() में क्या अंतर है?
Answer
| Method | Returns | Memory usage |
|---|---|---|
| read() | Entire file content as one string | High for large files - loads everything |
| readline() | One line at a time (as a string) | Low - reads incrementally |
| readlines() | List of ALL lines as strings | High - loads everything into a list |
# read() - entire file as one string
with open('data.txt') as f:
content = f.read()
print(type(content)) # <class 'str'>
# readline() - one line at a time, good for large files
with open('data.txt') as f:
line1 = f.readline()
line2 = f.readline()
print(line1, line2)
# readlines() - list of all lines
with open('data.txt') as f:
lines = f.readlines()
print(type(lines)) # <class 'list'>
for line in lines:
print(line.strip()) # strip() removes trailing \n
# MOST MEMORY-EFFICIENT: iterate the file object directly (like readline in a loop)
with open('large_file.txt') as f:
for line in f: # reads one line at a time, never loads the whole file
process(line.strip())
# This is the recommended approach for large files instead of readlines()| Method | Return | Memory usage |
|---|---|---|
| read() | पूरा content एक string | बड़ी files में ज़्यादा |
| readline() | एक-एक line | कम, incrementally |
| readlines() | सभी lines की list | ज़्यादा |
with open('data.txt') as f:
content = f.read()
print(type(content)) # str
with open('data.txt') as f:
line1 = f.readline()
line2 = f.readline()
with open('data.txt') as f:
lines = f.readlines()
for line in lines:
print(line.strip())
# सबसे memory-efficient - file object को सीधे iterate करना
with open('large_file.txt') as f:
for line in f:
process(line.strip())
# बड़ी files के लिए यह recommended है, readlines() से बेहतरWas this answer clear?