2011-03-24 65 views
13

我剛剛開始使用Python,但已經發現它比Bash shell腳本更有效率。Python程序遍歷目錄並讀取文件信息

我想寫一個Python腳本,將穿越每一個從目錄分支我啓動腳本目錄,併爲它遇到的每個文件,加載這個類的一個實例:

class FileInfo: 

    def __init__(self, filename, filepath): 
     self.filename = filename 
     self.filepath = filepath 

filepath屬性將是從根(/)開始的完整絕對路徑。下面是想我的主要程序做了僞樣機:

from (current directory): 

    for each file in this directory, 
    create an instance of FileInfo and load the file name and path 

    switch to a nested directory, or if there is none, back out of this directory 

我一直在閱讀有關os.walk()和ok.path.walk(),但我想一些建議關於在Python中實現這個最直接的方法是什麼。提前致謝。

+0

你想在哪裏分配創建的對象?這似乎是微不足道的。 – Ofir 2011-03-24 15:35:30

回答

17

我會使用os.walk執行以下操作:「。 「

def getInfos(currentDir): 
    infos = [] 
    for root, dirs, files in os.walk(currentDir): # Walk directory tree 
     for f in files: 
      infos.append(FileInfo(f,root)) 
    return infos 
+0

使用snake_case代替Python的CamelCase。 – franka 2014-04-21 12:43:42

7

嘗試

info = [] 
for path, dirs, files in os.walk("."): 
    info.extend(FileInfo(filename, path) for filename in files) 

info = [FileInfo(filename, path) 
     for path, dirs, files in os.walk(".") 
     for filename in files] 

,讓每一個文件實例FileInfo的列表。

1

試試吧

進口OS

在os.walk(項目」 *「):

 print item