0
0
Pythonprogramming~20 mins

Opening and closing files in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
File Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this file reading code?
Consider the following Python code that reads a file and prints its content. What will be printed?
Python
with open('test.txt', 'w') as f:
    f.write('Hello\nWorld')

with open('test.txt', 'r') as f:
    content = f.read()
print(content)
A
Hello
World
BHello World
C['Hello', 'World']
DError: file not found
Attempts:
2 left
💡 Hint
Remember that \n is a newline character and read() returns the whole content as a string.
Predict Output
intermediate
2:00remaining
What happens if you forget to close a file?
What will be the output or effect of this code snippet?
Python
f = open('sample.txt', 'w')
f.write('Data')
print('File written')
ANo output
BError: file not closed
CFile written
DData is not saved to file
Attempts:
2 left
💡 Hint
Think about what print() does and what happens if you don't close a file immediately.
Predict Output
advanced
2:00remaining
What is the output of this code using file context manager?
What will this code print?
Python
with open('numbers.txt', 'w') as f:
    for i in range(3):
        f.write(str(i))

with open('numbers.txt', 'r') as f:
    print(f.readline())
A0
BError: readline returns list
C1
D012
Attempts:
2 left
💡 Hint
readline() reads until the first newline or end of file.
Predict Output
advanced
2:00remaining
What error does this code raise?
What error will this code produce?
Python
f = open('nonexistent.txt', 'r')
content = f.read()
f.close()
AValueError
BFileNotFoundError
CTypeError
DNo error
Attempts:
2 left
💡 Hint
The file does not exist and is opened in read mode.
Predict Output
expert
3:00remaining
What is the value of 'lines' after this code runs?
Given this code, what is the value of the variable 'lines'?
Python
with open('data.txt', 'w') as f:
    f.write('line1\nline2\nline3')

with open('data.txt', 'r') as f:
    lines = f.readlines()

lines = [line.strip() for line in lines]
A['line1', 'line2', 'line3']
B['line1\n', 'line2\n', 'line3']
C['line1 line2 line3']
D['line1', 'line2', 'line3\n']
Attempts:
2 left
💡 Hint
readlines() returns lines with newline characters; strip() removes them.