在python中查找所有linux文件的通用目录

2024-09-30 01:28:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在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: '/'

Tags: 文件目录txthomelinuxrootdirectorygeneral
3条回答

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.


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

tuple giving access to the path’s various components.

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

这是我的密码:

def test(l):
l = [s.split('/') for s in l]
len_list = len(l)
min_len = min(len(s) for s in l)
i = 0
result = ''
while i < min_len:
    j = 1
    while j < len_list:
        if l[0][i] != l[j][i]:
            return result
        j += 1
    result = '%s%s/' % (result, l[0][i])
    i += 1
return result

相关问题 更多 >

    热门问题