Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 3 of 10 · File Handling & Context Managers
Interview question

What is the difference between read(), readline(), and readlines()? read(), readline(), और readlines() में क्या अंतर है?

Answer
MethodReturnsMemory usage
read()Entire file content as one stringHigh for large files - loads everything
readline()One line at a time (as a string)Low - reads incrementally
readlines()List of ALL lines as stringsHigh - 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()
MethodReturnMemory 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?