python - 在python中查找所有linux文件的总目录

标签 python linux algorithm

我想在 python 中找到所有 linux 文件的通用目录(不是目录)。大家能帮帮我吗?

示例 1:

['/home/tung/abc.txt', '/home/tung/xyz.txt']
    -> general directory: '/home/tung'

例子2:

['/home/tung/abc.txt', '/home/tung/xyz.txt', '/home/user/123.txt']
    -> general directory: '/home'

示例 3:

['/home/tung/abc.txt', '/root/xyz.txt']
    -> general directory: '/'

最佳答案

os.path.commonprefix(list)

Return the longest path prefix (taken character-by-character) that is a prefix of all paths in list. If list is empty, return the empty string (''). Note that this may return invalid paths because it works a character at a time.


或者,如果您使用的是 python 3.4+(我想这部分答案更适合 future ),您可以使用 pathlib 和: PurePaths.parts会给你一个

tuple giving access to the path’s various components.

将不同文件的元组转换为列表,然后找到common list of prefixes for a list of lists .

关于python - 在python中查找所有linux文件的总目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22373771/

相关文章:

python - 用\n替换其中的文本,用一个真实的\n输出

python - 使用 WHERE ___ IN ___ 语句

linux - Bash 脚本无法正确检查目录和文件是否存在

linux - 测量 Linux 多线程应用程序的堆栈使用情况

mysql - 我安装了 phpMyAdmin,并跳过了输入密码的步骤,现在无法做太多事情

python - 如何计算python3中大文本中排列(重叠)的出现次数?

python - float() 参数必须是字符串或数字,而不是 '_sre.SRE_Match'

python - Pandas 数据框重新定向

php - 根据键=>值对对数组进行排序

algorithm - 我如何分析k个空槽算法?