Recall & Review
beginner
What is the simplest way to open a file for reading in Python?
Use the
open() function with the filename and mode 'r', like open('filename.txt', 'r').Click to reveal answer
beginner
How do you read a file line by line using a for loop in Python?
You can loop directly over the file object: <br>
with open('file.txt', 'r') as f:<br> for line in f:<br> print(line)Click to reveal answer
beginner
Why is it good practice to use
with when opening files?Because
with automatically closes the file when done, even if errors happen. This helps avoid resource leaks.Click to reveal answer
intermediate
What does the
readline() method do?It reads the next single line from the file each time it is called, returning it as a string including the newline character.
Click to reveal answer
beginner
How can you remove the newline character from each line when reading a file?
Use the
strip() method on the line string, like line.strip(), to remove whitespace including newlines.Click to reveal answer
Which Python statement correctly reads a file line by line?
✗ Incorrect
Option B uses a with statement and loops directly over the file object, which is the recommended way to read lines one by one.
What does the 'r' mode mean in open('file.txt', 'r')?
✗ Incorrect
'r' stands for read mode, which opens the file only for reading.
What happens if you forget to close a file after reading?
✗ Incorrect
If you don't close a file, it remains open and can cause resource leaks or lock the file.
Which method reads one line at a time from a file?
✗ Incorrect
The readline() method reads the next single line from the file.
How can you remove extra spaces and newline characters from a line read from a file?
✗ Incorrect
The strip() method removes whitespace including newlines from the start and end of a string.
Explain how to read a file line by line in Python using a for loop.
Think about how you open the file and how you get each line one at a time.
You got /4 concepts.
Describe why using the with statement is important when working with files.
Consider what happens if your program crashes while the file is open.
You got /4 concepts.