0
0
Pythonprogramming~10 mins

Working with operating system paths in Python - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to join two parts of a file path using the os module.

Python
import os
path = os.path.[1]('folder', 'file.txt')
print(path)
Drag options to blanks, or click blank then click option'
Abasename
Bsplit
Cexists
Djoin
Attempts:
3 left
💡 Hint
Common Mistakes
Using os.path.split which breaks a path instead of joining.
Using os.path.exists which checks if a path exists, not joining.
2fill in blank
medium

Complete the code to get the directory name from a file path.

Python
import os
folder = os.path.[1]('/home/user/file.txt')
print(folder)
Drag options to blanks, or click blank then click option'
Adirname
Bbasename
Cjoin
Dsplitext
Attempts:
3 left
💡 Hint
Common Mistakes
Using basename which returns the file name, not the folder.
Using splitext which separates file extension.
3fill in blank
hard

Fix the error in the code to check if a path exists.

Python
import os
path = '/tmp/test.txt'
exists = os.path.[1](path)
print(exists)
Drag options to blanks, or click blank then click option'
Aexists
Bjoin
Cisfile
Ddirname
Attempts:
3 left
💡 Hint
Common Mistakes
Using join which combines paths, not checks existence.
Using dirname which gets folder name, not existence.
4fill in blank
hard

Fill both blanks to create a dictionary with file names as keys and their extensions as values.

Python
import os
files = ['doc.txt', 'image.png', 'script.pyc']
ext_dict = {f[1]: os.path.[2](f)[1] for f in files}
print(ext_dict)
Drag options to blanks, or click blank then click option'
A[:-4]
Bsplitext
Cbasename
D[-4:]
Attempts:
3 left
💡 Hint
Common Mistakes
Using basename which returns full file name including extension.
Using wrong slicing that does not remove extension correctly.
5fill in blank
hard

Fill all three blanks to filter files with '.txt' extension and get their absolute paths.

Python
import os
files = ['a.txt', 'b.py', 'c.txt']
txt_paths = [os.path.[1](f) for f in files if os.path.splitext(f)[[2]] == [3]]
print(txt_paths)
Drag options to blanks, or click blank then click option'
Aabspath
B1
C'.txt'
Dbasename
Attempts:
3 left
💡 Hint
Common Mistakes
Using basename which returns only file name, not full path.
Using index 0 which is file name without extension.
Comparing extension to wrong string.