To split a file path into its directory and filename components using the path
package in Python, you can use the split()
function from the os.path
module. Here is an example of how to do it:
import os
file_path = "/path/to/file/example.txt"
# Split the file path into directory and filename
directory, filename = os.path.split(file_path)
print("Directory:", directory)
print("Filename:", filename)
Output:
Directory: /path/to/file
Filename: example.txt
Alternatively, you can also use the pathlib
module, which provides an object-oriented approach:
from pathlib import Path
file_path = "/path/to/file/example.txt"
# Create a Path object from the file path
path_obj = Path(file_path)
# Split the Path object into directory and filename
directory = path_obj.parent
filename = path_obj.name
print("Directory:", directory)
print("Filename:", filename)
Output:
Directory: /path/to/file
Filename: example.txt
Both methods achieve the same result, so choose the one that best fits your coding style or requirements.