Reading Files

read, readline, readlines

Interview Relevant: File input

Reading Files

Code Examples

python
1with open("data.txt") as f:
2    text = f.read()       # Read all
3    f.seek(0)
4    line = f.readline()   # Read one line
5    f.seek(0)
6    lines = f.readlines() # List of lines
7    
8    # Iterate lines (memory efficient)
9    f.seek(0)
10    for line in f:
11        print(line.strip())

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In