Bird
Raised Fist0
Pythonprogramming~20 mins

Reading files line by line in Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
File Reader Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of reading lines with strip()
What is the output of this Python code that reads a file line by line and strips whitespace?
Python
with open('test.txt', 'w') as f:
    f.write('  line1  \nline2\n  line3  \n')

with open('test.txt', 'r') as file:
    lines = [line.strip() for line in file]
print(lines)
A['line1', 'line2', 'line3']
B[' line1 ', 'line2', ' line3 ']
C['line1 ', 'line2', 'line3 ']
D[' line1', 'line2', ' line3']
Attempts:
2 left
💡 Hint
The strip() method removes spaces at the start and end of each line.
Predict Output
intermediate
2:00remaining
Reading file lines with readlines()
What will be the output of this code that reads lines from a file using readlines()?
Python
with open('test2.txt', 'w') as f:
    f.write('apple\nbanana\ncherry\n')

with open('test2.txt', 'r') as f:
    fruits = f.readlines()
print(fruits)
A['apple banana cherry']
B['apple\n', 'banana\n', 'cherry\n']
C['apple', 'banana', 'cherry']
D['apple\r\n', 'banana\r\n', 'cherry\r\n']
Attempts:
2 left
💡 Hint
readlines() keeps the newline characters at the end of each line.
🔧 Debug
advanced
2:00remaining
Why does this code raise an error?
This code tries to read a file line by line but raises an error. What is the cause?
Python
file = open('missing.txt', 'r')
for line in file:
    print(line)
file.close()
ATypeError because file is not iterable
BSyntaxError because the for loop is missing a colon
CFileNotFoundError because the file 'missing.txt' does not exist
DIndentationError because print is not indented
Attempts:
2 left
💡 Hint
Check if the file exists before opening it.
Predict Output
advanced
2:00remaining
Output of reading file with a while loop
What is the output of this code that reads a file line by line using a while loop?
Python
with open('test3.txt', 'w') as f:
    f.write('one\ntwo\nthree\n')

with open('test3.txt', 'r') as f:
    line = f.readline()
    lines = []
    while line:
        lines.append(line.strip())
        line = f.readline()
print(lines)
A['one', 'two', 'three']
B['one\ntwo\nthree\n']
C['one', 'two', 'three', '']
D['one', 'two', 'three', None]
Attempts:
2 left
💡 Hint
readline() returns an empty string when the file ends.
Predict Output
expert
2:00remaining
Number of lines read with a generator expression
What is the number of lines read by this code using a generator expression?
Python
with open('test4.txt', 'w') as f:
    f.write('a\nb\nc\nd\n')

with open('test4.txt', 'r') as f:
    count = sum(1 for _ in f if _.strip() != 'b')
print(count)
A1
B4
C2
D3
Attempts:
2 left
💡 Hint
Count lines except those equal to 'b' after stripping.

Practice

(1/5)
1. What does the following code do?
with open('data.txt') as file:
    for line in file:
        print(line)
easy
A. Creates a new file named 'data.txt'
B. Reads the whole file at once and prints it
C. Writes lines to 'data.txt'
D. Reads and prints each line from 'data.txt' including newline characters

Solution

  1. Step 1: Understand the with open statement

    The code opens 'data.txt' for reading and ensures it closes automatically after use.
  2. Step 2: Analyze the for loop over the file object

    Looping over the file reads it line by line, printing each line including its newline character.
  3. Final Answer:

    Reads and prints each line from 'data.txt' including newline characters -> Option D
  4. Quick Check:

    Reading lines one by one = Reads and prints each line from 'data.txt' including newline characters [OK]
Hint: Looping file reads lines one by one including newlines [OK]
Common Mistakes:
  • Thinking it reads whole file at once
  • Confusing reading with writing
  • Assuming it creates a file
2. Which of these is the correct syntax to read a file line by line in Python?
easy
A. with open('file.txt') as f: for line in f: print(line)
B. open('file.txt') for line in f: print(line)
C. with open('file.txt') as f: while line in f: print(line)
D. with open('file.txt') as f: for line in file: print(line)

Solution

  1. Step 1: Check the correct use of with open

    with open('file.txt') as f: for line in f: print(line) correctly uses 'with open(filename) as f:' to open the file safely.
  2. Step 2: Verify the for loop syntax

    with open('file.txt') as f: for line in f: print(line) uses 'for line in f:' which is the proper way to iterate lines in the file object.
  3. Final Answer:

    with open('file.txt') as f:\n for line in f:\n print(line) -> Option A
  4. Quick Check:

    Correct with open and for loop syntax = with open('file.txt') as f: for line in f: print(line) [OK]
Hint: Use 'with open' and 'for line in file' to read lines [OK]
Common Mistakes:
  • Missing 'with' keyword
  • Using wrong loop syntax like 'while line in f'
  • Using undefined variable 'file' instead of 'f'
3. What will be the output of this code if 'test.txt' contains:\nLine1\nLine2\n\nLine4\n?
with open('test.txt') as f:
    for line in f:
        print(line.strip())
medium
A. Line1\nLine2\n\nLine4
B. Line1\nLine2\n\n\nLine4
C. Line1\nLine2\nLine4
D. Line1\nLine2\nLine4\n

Solution

  1. Step 1: Understand strip() effect on lines

    strip() removes whitespace including newlines, so empty lines become empty strings.
  2. Step 2: Analyze printing each stripped line

    Empty lines print as blank lines, but print() adds a newline, so empty lines show as blank lines.
  3. Final Answer:

    Line1\nLine2\n\nLine4 -> Option A
  4. Quick Check:

    strip() on empty -> '', print('') = blank line = Line1\nLine2\n\nLine4 [OK]
Hint: strip() removes newlines, print adds one newline per line [OK]
Common Mistakes:
  • Assuming strip() keeps newlines
  • Confusing blank lines with extra newlines
  • Ignoring print() adds newline automatically
4. Find the error in this code snippet:
with open('file.txt') as f:
    for line in file:
        print(line)
medium
A. Indentation error inside the loop
B. Missing colon after for loop
C. Variable 'file' is undefined; should use 'f' instead
D. File not opened in write mode

Solution

  1. Step 1: Check variable names used in the loop

    The file is opened as 'f', but the loop uses 'file' which is undefined.
  2. Step 2: Confirm correct variable usage

    Changing 'file' to 'f' fixes the error and allows reading lines properly.
  3. Final Answer:

    Variable 'file' is undefined; should use 'f' instead -> Option C
  4. Quick Check:

    Use same variable name as in with open = Variable 'file' is undefined; should use 'f' instead [OK]
Hint: Use same variable name from with open in for loop [OK]
Common Mistakes:
  • Using different variable names
  • Assuming file is a keyword
  • Ignoring variable scope inside with block
5. You want to read a large log file line by line and count how many lines contain the word 'error'. Which code snippet correctly does this?
hard
A. count = 0 with open('log.txt') as f: lines = f.readlines() for line in lines: if 'error' in line: count += 1 print(count)
B. count = 0 with open('log.txt') as f: for line in f: if 'error' in line: count += 1 print(count)
C. count = 0 f = open('log.txt') lines = f.readlines() for line in lines: if 'error' in line: count += 1 f.close() print(count)
D. count = 0 with open('log.txt') as f: for line in f: if line == 'error': count += 1 print(count)

Solution

  1. Step 1: Choose efficient line-by-line reading

    count = 0 with open('log.txt') as f: for line in f: if 'error' in line: count += 1 print(count) uses 'with open' and iterates file line by line, which is memory efficient for large files.
  2. Step 2: Check condition for counting 'error' in line

    count = 0 with open('log.txt') as f: for line in f: if 'error' in line: count += 1 print(count) correctly checks if 'error' is anywhere in the line and increments count.
  3. Final Answer:

    count = 0\nwith open('log.txt') as f:\n for line in f:\n if 'error' in line:\n count += 1\nprint(count) -> Option B
  4. Quick Check:

    Efficient reading + correct condition = count = 0 with open('log.txt') as f: for line in f: if 'error' in line: count += 1 print(count) [OK]
Hint: Use with open and for line in file for big files [OK]
Common Mistakes:
  • Using readlines() for big files (memory issue)
  • Forgetting to close file without with
  • Checking line equality instead of substring