0
0
Pythonprogramming~10 mins

File path handling 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 folder and filename into a full path using pathlib.

Python
from pathlib import Path
folder = Path('documents')
filename = 'file.txt'
full_path = folder[1]filename
print(full_path)
Drag options to blanks, or click blank then click option'
A+
B\
C/
D.
Attempts:
3 left
💡 Hint
Common Mistakes
Using '+' to join paths instead of '/'
Using string concatenation instead of pathlib methods
2fill in blank
medium

Complete the code to get the file extension from a path using pathlib.

Python
from pathlib import Path
file_path = Path('archive.zip')
extension = file_path[1]
print(extension)
Drag options to blanks, or click blank then click option'
A.suffix
B.ext
C.extension
D.name
Attempts:
3 left
💡 Hint
Common Mistakes
Using '.ext' which does not exist
Using '.name' which returns the filename
3fill in blank
hard

Fix the error in the code to check if a path is a directory using pathlib.

Python
from pathlib import Path
path = Path('/usr/bin')
if path[1]():
    print('It is a directory')
Drag options to blanks, or click blank then click option'
A.is_file
B.is_dir
C.is_directory
D.exists
Attempts:
3 left
💡 Hint
Common Mistakes
Using '.is_directory()' which does not exist
Using '.exists()' which only checks if path exists
4fill in blank
hard

Fill both blanks to create a dictionary with filenames as keys and their sizes as values.

Python
from pathlib import Path
files = [Path('a.txt'), Path('b.txt'), Path('c.txt')]
sizes = { [1]: file.stat().st_size for file in files if file[2]() }
print(sizes)
Drag options to blanks, or click blank then click option'
Afile.name
B.is_file
C.is_dir
Dfile.path
Attempts:
3 left
💡 Hint
Common Mistakes
Using '.is_dir()' instead of '.is_file()'
Using 'file.path' which is not a valid attribute
5fill in blank
hard

Fill all three blanks to create a dictionary with uppercase filenames as keys, file sizes as values, filtering files larger than 1000 bytes.

Python
from pathlib import Path
files = [Path('x.log'), Path('y.log'), Path('z.log')]
result = { [1]: [2] for f in files if f.is_file() and f.stat().st_size [3] 1000 }
print(result)
Drag options to blanks, or click blank then click option'
Af.name.upper()
Bf.stat().st_size
C>
D<=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<=' instead of '>' for filtering
Using 'f.name' without uppercasing