0
0
Pythonprogramming~20 mins

File path handling in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
File Path 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 using pathlib?
Consider the following Python code that uses pathlib to manipulate file paths. What will be printed?
Python
from pathlib import Path
p = Path('/home/user/docs')
new_path = p / 'projects' / '..' / 'notes.txt'
print(new_path.resolve())
A/home/user/docs/projects/../notes.txt
B/home/user/projects/notes.txt
C/home/user/docs/notes.txt
D/home/user/docs/projects/notes.txt
Attempts:
2 left
💡 Hint
Remember that '..' means to go up one directory, and resolve() simplifies the path.
Predict Output
intermediate
2:00remaining
What does this os.path code output?
Given this Python code using os.path, what will be the output?
Python
import os
path = '/var/log/syslog'
print(os.path.basename(os.path.dirname(path)))
Asyslog
Blog
C/var/log
Dvar
Attempts:
2 left
💡 Hint
os.path.dirname() gets the folder path, and os.path.basename() gets the last part of a path.
Predict Output
advanced
2:00remaining
What is the output of this code using pathlib's parts?
Look at this code that uses pathlib.Path.parts. What will it print?
Python
from pathlib import Path
p = Path('/usr/local/bin/python3')
print(p.parts[2])
Apython3
Busr
Cbin
Dlocal
Attempts:
2 left
💡 Hint
The parts attribute splits the path into a tuple starting with root '/' as the first part.
Predict Output
advanced
2:00remaining
What error does this code raise?
What error will this Python code raise when run?
Python
import os
path = '/tmp/testfile.txt'
print(os.path.join(path, 'subdir'))
ANo error, output: '/tmp/testfile.txt/subdir'
BValueError
CTypeError
DNo error, output: '/tmp/subdir'
Attempts:
2 left
💡 Hint
Check how os.path.join works when the first argument is an absolute path.
🧠 Conceptual
expert
3:00remaining
Which option correctly normalizes a Windows path?
You have a Windows path string with mixed slashes: "C:/Users\\Admin/../Documents\\file.txt". Which option correctly normalizes it to a clean absolute path using Python?
AUse <code>os.path.normpath('C:/Users\\Admin/../Documents\\file.txt')</code>
BUse <code>Path('C:/Users\\Admin/../Documents\\file.txt').resolve()</code>
CUse <code>os.path.abspath('C:/Users\\Admin/../Documents\\file.txt')</code>
DUse <code>Path('C:/Users\\Admin/../Documents\\file.txt').absolute()</code>
Attempts:
2 left
💡 Hint
Normalization fixes slashes and removes '..' parts without requiring the file to exist.