Challenge - 5 Problems
File Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
Remember that \n is a newline character and read() returns the whole content as a string.
✗ Incorrect
The file is written with 'Hello\nWorld', so reading it returns the string with a newline. Printing it shows Hello and World on separate lines.
❓ Predict Output
intermediate2: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')
Attempts:
2 left
💡 Hint
Think about what print() does and what happens if you don't close a file immediately.
✗ Incorrect
The print statement runs and outputs 'File written'. The file may not be flushed immediately but no error occurs.
❓ Predict Output
advanced2: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())
Attempts:
2 left
💡 Hint
readline() reads until the first newline or end of file.
✗ Incorrect
The file contains '012' without newlines. readline() reads until newline or EOF, so it returns '012'. But since no newline, it returns all. So output is '012'.
❓ Predict Output
advanced2:00remaining
What error does this code raise?
What error will this code produce?
Python
f = open('nonexistent.txt', 'r') content = f.read() f.close()
Attempts:
2 left
💡 Hint
The file does not exist and is opened in read mode.
✗ Incorrect
Trying to open a file that does not exist in read mode raises FileNotFoundError.
❓ Predict Output
expert3: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]
Attempts:
2 left
💡 Hint
readlines() returns lines with newline characters; strip() removes them.
✗ Incorrect
readlines() returns list with newlines. The list comprehension removes newlines, so lines contains clean strings.