How to circumvent the fallacy of Python's os.path.commonprefix?

后端 未结 5 1273
耶瑟儿~
耶瑟儿~ 2020-12-18 19:00

My problem is to find the common path prefix of a given set of files.

Literally I was expecting that \"os.path.commonprefix\" would do just that. Unfortunat

5条回答
  •  轮回少年
    2020-12-18 19:19

    Assuming you want the common directory path, one way is to:

    1. Use only directory paths as input. If your input value is a file name, call os.path.dirname(filename) to get its directory path.
    2. "Normalize" all the paths so that they are relative to the same thing and don't include double separators. The easiest way to do this is by calling os.path.abspath( ) to get the path relative to the root. (You might also want to use os.path.realpath( ) to remove symbolic links.)
    3. Add a final separator (found portably with os.path.sep or os.sep) to the end of all the normalized directory paths.
    4. Call os.path.dirname( ) on the result of os.path.commonprefix( ).

    In code (without removing symbolic links):

    def common_path(directories):
        norm_paths = [os.path.abspath(p) + os.path.sep for p in directories]
        return os.path.dirname(os.path.commonprefix(norm_paths))
    
    def common_path_of_filenames(filenames):
        return common_path([os.path.dirname(f) for f in filenames])
    

提交回复
热议问题