How to extract the directory part from a file path using the path package?

To extract the directory part from a file path using the path package in python, you can use the pathlib module which is a part of the standard library. Here's an example:

from pathlib import Path # Example file path file_path = '/home/user/documents/file.txt' # Use Path to convert the string to a Path object path_object = Path(file_path) # Get the directory part of the file path directory = path_object.parent # Convert the directory to a string directory_str = str(directory) # Print the directory part print(directory_str)

In this example, we first import the Path class from the pathlib module. Then, we define a file path using a string variable (file_path). Next, we create a Path object (path_object) by passing the file path string to the Path() constructor.

To retrieve the directory part of the file path, we access the parent attribute of the path_object. This will give us a new Path object representing the directory of the file.

Finally, we convert the directory object to a string using the str() function and print it out. The output will be the directory part of the file path (/home/user/documents in this case).