To find the common parent directory of multiple file paths using the path package, you can follow these steps:
path
module from the pathlib
package:from pathlib import Path
file_paths = ['/path/to/file1.txt', '/path/to/file2.txt', '/path/to/folder/file3.txt']
Path
objects:path_objects = [Path(file_path) for file_path in file_paths]
Path
object's parents
attribute to get a list of the parent directories for each file path:parent_directories = [path.parents for path in path_objects]
common_parent = set.intersection(*parent_directories)
common_parent
set is not empty, get the first element as the common parent directory path:if common_parent:
common_parent_directory = common_parent.pop()
common_parent_directory = str(common_parent_directory) # Convert Path object to string
Here is the complete code:
from pathlib import Path
file_paths = ['/path/to/file1.txt', '/path/to/file2.txt', '/path/to/folder/file3.txt']
path_objects = [Path(file_path) for file_path in file_paths]
parent_directories = [path.parents for path in path_objects]
common_parent = set.intersection(*parent_directories)
if common_parent:
common_parent_directory = common_parent.pop()
common_parent_directory = str(common_parent_directory) # Convert Path object to string
print(common_parent_directory)
Running this code will print the common parent directory path.