Challenge - 5 Problems
File Writing Master
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 write operation?
Consider this Python code that writes to a file and then reads it back. What will be printed?
Python
with open('testfile.txt', 'w') as f: f.write('Hello\nWorld') with open('testfile.txt', 'r') as f: content = f.read() print(content)
Attempts:
2 left
💡 Hint
Remember that '\n' is a newline character in strings.
✗ Incorrect
The write method writes the string with a newline character, so when reading back, the content has two lines: 'Hello' and 'World'.
❓ Predict Output
intermediate2:00remaining
What happens if you write to a file opened in append mode?
Given this code, what will be the content of 'append.txt' after running it twice?
Python
with open('append.txt', 'a') as f: f.write('Line\n')
Attempts:
2 left
💡 Hint
Append mode adds data to the end of the file without deleting existing content.
✗ Incorrect
Opening a file in append mode ('a') adds new data to the end. Running twice adds two lines.
❓ Predict Output
advanced2:00remaining
What is the output of this code that writes and reads binary data?
Look at this Python code that writes bytes to a file and then reads it back. What will be printed?
Python
data = b'\x48\x65\x6c\x6c\x6f' with open('binary.dat', 'wb') as f: f.write(data) with open('binary.dat', 'rb') as f: content = f.read() print(content)
Attempts:
2 left
💡 Hint
Binary mode reads and writes bytes, so the output is a bytes object.
✗ Incorrect
The bytes written are the ASCII codes for 'Hello'. Reading in binary mode returns the same bytes object.
❓ Predict Output
advanced2:00remaining
What error does this code raise when writing to a file opened in read mode?
What happens when you try to write to a file opened with mode 'r'?
Python
with open('file.txt', 'r') as f: f.write('Test')
Attempts:
2 left
💡 Hint
Files opened in read mode do not allow writing.
✗ Incorrect
Trying to write to a file opened in 'r' mode raises an io.UnsupportedOperation error because the file is not writable.
🧠 Conceptual
expert2:00remaining
How many lines will be in the file after running this code?
This code writes lines to a file inside a loop. How many lines will the file contain after running it once?
Python
with open('lines.txt', 'w') as f: for i in range(5): f.write(f'Line {i}\n') f.write('End')
Attempts:
2 left
💡 Hint
Count the lines written including the last write without a newline.
✗ Incorrect
The loop writes 5 lines each ending with a newline, then one more line 'End' without newline, so total lines are 6.