[英]Find general directory of all linux files in 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: '/'
返回最長路徑前綴(逐個字符取),它是列表中所有路徑的前綴。 如果列表為空,則返回空字符串 ('')。 請注意,這可能會返回無效路徑,因為它一次只處理一個字符。
或者,如果您使用的是 python 3.4+(我想這部分答案在未來更適用),您可以使用pathlib
和: PurePaths.parts會給您一個
元組可以訪問路徑的各種組件。
它已在 RosettaCode 上完成: http: //rosettacode.org/wiki/Find_common_directory_path#Python
這是我的代碼:
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
更進一步@romaj 的答案,這里是基於commonprefix()
的實現,它為['/home/tung/abc.txt', '/home/tung123/xyz.txt']
生成正確答案/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
使用 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.