0
0
Pythonprogramming~20 mins

File system interaction basics in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
File System Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Reading a file's content
What is the output of this code if the file example.txt contains the text Hello World?
Python
with open('example.txt', 'r') as f:
    content = f.read()
print(content)
A"Hello World"
B['Hello World']
Cb'Hello World'
DNone
Attempts:
2 left
💡 Hint
The read() method returns the whole file content as a string.
Predict Output
intermediate
2:00remaining
Writing and reading back a file
What will be printed after running this code?
Python
with open('testfile.txt', 'w') as f:
    f.write('12345')
with open('testfile.txt', 'r') as f:
    print(f.readline())
A12345
B['12345']
CNone
D1
Attempts:
2 left
💡 Hint
The write method writes text, and readline reads one line as a string.
Predict Output
advanced
2:00remaining
Using os.path to check file existence
What does this code print if the file data.txt does NOT exist in the current folder?
Python
import os
if os.path.exists('data.txt'):
    print('Found')
else:
    print('Not Found')
AFound
BNot Found
CRaises FileNotFoundError
DNone
Attempts:
2 left
💡 Hint
The os.path.exists function returns True if the file exists, otherwise False.
Predict Output
advanced
2:00remaining
Understanding file modes and errors
What error does this code raise if readonly.txt exists but is read-only?
Python
with open('readonly.txt', 'w') as f:
    f.write('Trying to write')
ANo error, writes successfully
BTypeError
CPermissionError
DFileNotFoundError
Attempts:
2 left
💡 Hint
Opening a read-only file for writing usually causes a permission error.
🧠 Conceptual
expert
2:00remaining
File pointer position after reading
After running this code, what is the value of pos?
Python
with open('numbers.txt', 'w') as f:
    f.write('1234567890')
with open('numbers.txt', 'r') as f:
    f.read(4)
    pos = f.tell()
print(pos)
A10
B0
CRaises an error
D4
Attempts:
2 left
💡 Hint
The tell() method returns the current position of the file pointer.