2016-12-24 161 views
3

我想列出所有目錄(/ home/dir下面的一個級別)和它的內容。此代碼正在工作,但是當我將字典轉換爲熊貓數據框時,目錄名稱與文件名稱不匹配。遍歷目錄路徑

mypath='/home/' 
from os import walk 

myd=dict() 
for (dirpath, dirnames, filenames) in walk(mypath): 
    for i in dirnames: 
     for (dirpath1, dirnames1, filenames1) in walk(i): 
      myd[i]=','.join(filenames1) 


import pandas as pd 
df=pd.DataFrame(myd , index=[0]).T 
df.columns=['files'] 

pd.set_option('max_colwidth', 800) 
df 

有沒有更好的方法來建立2列數據幀的目錄和它的文件內容?

回答

2

我不完全確定你的最終結果應該是什麼樣子,但os.walk爲你做了完整的遞歸!沒有必要在第二循環遍歷dirnames

import os 

mypath = '/home/' 

myd = {} 
for (here, dirs, files) in os.walk(mypath): 
    for file in files: 
     myd[here] = '.'.join(files) 

print(myd) 

這是蟒3代碼;它蟒蛇2 file是一個關鍵字,不應該被用來作爲變量名...

UPDATE

如果你只需要輸入目錄的下一級沒有必要walk

myd = {} 
for name in os.listdir(mypath): 
    subdir = os.path.join(mypath, name) 
    if not os.path.isdir(subdir): 
     continue 
    myd[name] = '.'.join(os.listdir(subdir)) 

print(myd)