2014-03-13 67 views
2

我想在python中找到所有linux文件(不是目錄)的通用目錄。每個人都可以幫我嗎?在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: '/' 

回答

5

os.path.commonprefix(list)

返回列表中所有路徑前綴的最長路徑前綴(逐字符)。如果列表爲空,則返回空字符串('')。請注意,這可能會返回無效的路徑,因爲它一次處理一個字符。


或者,如果你正在使用python 3.4+(我猜的答案,這部分多爲將來的),你可以使用pathlib和: PurePaths.parts會給你一個

元組訪問路徑的各種組件。

將不同文件的元組轉換爲列表,然後找到common list of prefixes for a list of lists

+1

謝謝radomaj! 如果我使用os.path.commonprefix(列表),你的結果將是: ['/home/tung/abc.txt','/home/tung123/xyz.txt'] - > general directory:'/ '/ home /':) – user3414482

+0

@ user3414482:在這種情況下,你可以使用commonprefix()來獲得'/ home'](http:// stackoverflow .com/a/22387892/4279) – jfs

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 
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 
相關問題