0
0
Pythonprogramming~20 mins

File modes and access types in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
File Mode 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 code when reading a file?

Consider a file example.txt containing the text "Hello World". What will be printed by the following code?

Python
with open('example.txt', 'r') as f:
    content = f.read(5)
    print(content)
A"Hello World"
B"Hello\n"
C"Hello"
D"World"
Attempts:
2 left
💡 Hint

The read(n) method reads n characters from the file starting at the beginning.

Predict Output
intermediate
2:00remaining
What happens when opening a file in 'w' mode?

Given a file data.txt that already contains some text, what will be the content of the file after running this code?

Python
with open('data.txt', 'w') as f:
    f.write('New content')
AThe code will raise an error because the file exists.
BThe file will contain the old content plus "New content" appended.
CThe file will be unchanged.
DThe file will contain "New content" only.
Attempts:
2 left
💡 Hint

Opening a file in 'w' mode clears its content before writing.

Predict Output
advanced
2:00remaining
What error does this code raise when opening a non-existent file?

What error will this code raise if missing.txt does not exist?

Python
with open('missing.txt', 'r') as f:
    data = f.read()
AFileNotFoundError
BPermissionError
CIsADirectoryError
DNo error, file is created automatically
Attempts:
2 left
💡 Hint

Opening a file in read mode requires the file to exist.

Predict Output
advanced
2:00remaining
What is the content of the file after this code runs?

Assume log.txt initially contains "Start\n". What will be the content after running this code?

Python
with open('log.txt', 'a') as f:
    f.write('End\n')
A"End\n"
B"Start\nEnd\n"
C"Start\n"
DThe file is empty
Attempts:
2 left
💡 Hint

Mode 'a' appends to the file without deleting existing content.

🧠 Conceptual
expert
2:00remaining
Which file mode allows both reading and writing without truncating the file?

Choose the file mode that opens a file for both reading and writing, but does not erase the existing content when opened.

A"r+"
B"w+"
C"a+"
D"x+"
Attempts:
2 left
💡 Hint

One mode allows reading and writing and keeps existing content intact.