0
0
Pythonprogramming~20 mins

Writing file data in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
File Writing Master
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 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)
A
Hello
World
BHello World
CHello\nWorld
DSyntaxError
Attempts:
2 left
💡 Hint
Remember that '\n' is a newline character in strings.
Predict Output
intermediate
2: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')
AThe file will contain 'Line\nLine\n'
BThe file will contain only 'Line\n'
CThe file will be overwritten with 'Line\n'
DRaises an error because 'a' mode does not allow writing
Attempts:
2 left
💡 Hint
Append mode adds data to the end of the file without deleting existing content.
Predict Output
advanced
2: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)
Ab'\x48\x65\x6c\x6c\x6f'
B'Hello'
Cb'Hello'
DUnicodeDecodeError
Attempts:
2 left
💡 Hint
Binary mode reads and writes bytes, so the output is a bytes object.
Predict Output
advanced
2: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')
AFileNotFoundError
Bio.UnsupportedOperation: not writable
CTypeError
DNo error, writes successfully
Attempts:
2 left
💡 Hint
Files opened in read mode do not allow writing.
🧠 Conceptual
expert
2: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')
A5
B7
C4
D6
Attempts:
2 left
💡 Hint
Count the lines written including the last write without a newline.