Complete the code to join two parts of a file path using the os module.
import os path = os.path.[1]('folder', 'file.txt') print(path)
The os.path.join function combines parts of a path correctly for your operating system.
Complete the code to get the directory name from a file path.
import os folder = os.path.[1]('/home/user/file.txt') print(folder)
os.path.dirname returns the directory part of a file path.
Fix the error in the code to check if a path exists.
import os path = '/tmp/test.txt' exists = os.path.[1](path) print(exists)
os.path.exists checks if the given path exists on the system.
Fill both blanks to create a dictionary with file names as keys and their extensions as values.
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)
We slice the file name to remove the last 4 characters (extension) for the key, and use splitext to get the extension as value.
Fill all three blanks to filter files with '.txt' extension and get their absolute paths.
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)
os.path.abspath gets the full path, splitext(f)[1] gets the extension, and we compare it to '.txt' to filter only text files.