2017-12-18 187 views
1

我得到了與路徑的文本文件,如:文件名以及其作爲字典的路徑沒有顯示所有結果

/path/to/file.ext

我需要這些路徑分成字典所以key將排除路徑文件和value - 文件名及其擴展名。我曾與下面的代碼管理這樣的:

base = {} 
with open ('text.txt') as f: 
    for line in f: 
     key,val = line.strip('\n').rsplit('/',1) 
     base[key] = val 

我用.strip('\n')擺脫換行和.rsplit('/',1)基於路徑中的最後/分裂我的整個路徑。

該代碼基本上正在工作,但是...它不處理整個txt文件。

處理9900+路徑的文件,我得到了少於3000個元素(鍵+值)的基礎。我檢查了使用len(base)

  1. 所有的路徑,使用bash find命令做出這樣都OK。
  2. 路徑名稱不包含任何古怪的字符。
  3. 刪除.strip('\n')不會改變任何內容。我使用Python 2.7.10
+2

後如果兩個路徑具有第二個將覆蓋第一個。此外,它是可信的,不要自己做路徑處理。 –

回答

2

使用os.path模塊來處理目錄。 假設有一行/path/to/file.ext,下面的代碼

import os 

with open('test.txt') as f: 
    for line in f: 
     line = line.strip() 
     print(os.path.dirname(line)) 
     print(os.path.basename(line)) 

輸出

/path/to 
file.ext 

現在,@威廉·Onsem在註釋中解釋文件,使用os.path.dirname爲重點,將覆蓋以前的路徑文件在同一個目錄中。爲了解決這個問題,你需要使用列表作爲值:

import os 
from collections import defaultdict 

d = defaultdict(list) 

with open('test.txt') as f: 
    for line in f: 
     line = line.strip() 
     d[os.path.dirname(line)].append(os.path.basename(line)) 

現在考慮:

/path/to/file1.ext 
/path/to/file2.ext 
/path/to/file3.ext 
/another/path/to/file4.ext 

運行上面的代碼,print(d)將輸出

defaultdict(<class 'list'>, {'/path/to': ['file1.ext', 'file2.ext', 'file3.ext'], 
          '/another/path/to': ['file4.ext']}) 
+0

謝謝,現在我已經掌握了將所有行/路徑變成字典!現在我需要思考,如何處理它們 - 如何搜索單個文件並獲取它的路徑。 – mcskrzypczak

相關問題