0
0
Pythonprogramming~20 mins

Working with operating system paths in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
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 joining paths?
Consider the following Python code using os.path.join. What will be printed?
Python
import os
path = os.path.join('folder', 'subfolder', 'file.txt')
print(path)
A"folder.subfolder.file.txt"
B"folder/subfolder/file.txt"
C"folder-subfolder-file.txt"
D"folder\\subfolder\\file.txt"
Attempts:
2 left
💡 Hint
Think about how paths are joined on Unix-like systems.
Predict Output
intermediate
2:00remaining
What does os.path.basename return?
What will the following code print?
Python
import os
filename = os.path.basename('/home/user/docs/report.pdf')
print(filename)
A"report.pdf"
B"/home/user/docs/report.pdf"
C"/home/user/docs"
D"docs/report.pdf"
Attempts:
2 left
💡 Hint
Think about what the basename function extracts from a path.
Predict Output
advanced
2:00remaining
What is the output of normpath with redundant separators?
What will this code print?
Python
import os
path = os.path.normpath('folder//subfolder/../file.txt')
print(path)
A"folder//file.txt"
B"folder/../file.txt"
C"folder/file.txt"
D"folder/subfolder/file.txt"
Attempts:
2 left
💡 Hint
Think about how normpath simplifies paths by removing redundant parts.
Predict Output
advanced
2:00remaining
What error does this code raise?
What error will this code raise?
Python
import os
path = os.path.join('folder', None, 'file.txt')
print(path)
ATypeError
BValueError
CAttributeError
DNo error, prints 'folder/None/file.txt'
Attempts:
2 left
💡 Hint
Consider what happens when you pass None to os.path.join.
🧠 Conceptual
expert
2:00remaining
How many items are in the list after splitting a path?
Given this code, how many items will the list parts contain?
Python
import os
path = '/usr/local/bin/python3'
parts = path.split(os.sep)
print(len(parts))
A4
B3
C6
D5
Attempts:
2 left
💡 Hint
Remember that splitting by '/' on an absolute path creates an empty string at the start.