0
0
Pythonprogramming~5 mins

Reading files line by line in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Aopen('file.txt').read()
Bwith open('file.txt') as f: for line in f: print(line)
Cfile.read('file.txt')
Dfor line in open('file.txt').readlines(): print(line)
What does the 'r' mode mean in open('file.txt', 'r')?
AAppend mode, adds to the end
BWrite mode, opens file for writing
CRead mode, opens file for reading
DRead and write mode
What happens if you forget to close a file after reading?
AThe file stays open, which can cause resource leaks
BNothing, Python closes it automatically always
CThe file deletes itself
DThe file content is lost
Which method reads one line at a time from a file?
Aread()
Bopen()
Creadlines()
Dreadline()
How can you remove extra spaces and newline characters from a line read from a file?
Aline.strip()
Bline.remove()
Cline.clear()
Dline.delete()
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.