我想在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: '/'
答案 0 :(得分:5)
返回列表中所有路径的前缀的最长路径前缀(逐个字符)。如果list为空,则返回空字符串('')。请注意,这可能会返回无效路径,因为它一次只能处理一个字符。
或者,如果您使用的是Python 3.4+(我想这部分答案将来会更多),您可以使用pathlib
和:
PurePaths.parts会给你一个
元组可以访问路径的各个组件。
将不同文件的元组转换为列表,然后找到common list of prefixes for a list of lists。
答案 1 :(得分:1)
已在RosettaCode上完成:http://rosettacode.org/wiki/Find_common_directory_path#Python
答案 2 :(得分:0)
这是我的代码:
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
答案 3 :(得分:0)
更进一步@radomaj's answer,这是基于commonprefix()
的实现,为/home
输入文件生成正确答案/home/tung
而不是{无效} ['/home/tung/abc.txt', '/home/tung123/xyz.txt']
:
#!/usr/bin/env python
import os
try:
from pathlib import PurePath
except ImportError: # Python < 3.4
def get_parts(path):
path = os.path.dirname(path) # start with the parent directory
parts = []
previous = None
while path != previous:
previous = path
path, tail = os.path.split(path)
parts.append(tail)
parts.append(path)
parts.reverse()
return parts
else: # pathlib is available
def get_parts(path):
return PurePath(path).parent.parts
def commondir(files):
files_in_parts = list(map(get_parts, files))
return os.path.join(*os.path.commonprefix(files_in_parts))
示例:
print(commondir(['/home/tung/abc.txt', '/home/tung123/xyz.txt']))
# -> /home
答案 4 :(得分:0)
使用Python3更新2020:
def iscommon(a: PurePath, b: PurePath) -> bool:
"""Determine if paths have common root"""
length = min(len(a.parts), len(b.parts))
for i in range(length):
if a.parts[i] != b.parts[i]:
return False
return True