2013-06-06 54 views
0

我一直在試圖列出目錄中的所有文件,它的子目錄,其路徑和它的大小在python中。 不知何故,只顯示其目錄中的文件,而不顯示子目錄中的文件。Python的文件路徑和大小

import os 
from os.path import join, getsize,abspath, isfile 

fo=open("Size Listing.txt","a") 


def size_list(mypath): 
f = [] 
for (dirpath, dirname, filenames) in os.walk(mypath): 
    f.extend(filenames) 

for i in f: 
    fo.write("\nPath: ") 
    fo.write(abspath(i)) 
    fo.write(" Size: ") 
    fo.write(str(getsize(join(mypath,i)))) 
    fo.write(" bytes") 


fo.close() 

有人可以幫我嗎? 也可以任何人建議如何在Python中爲文件路徑和大小製作數據結構,因爲我還需要進行一些排序。 謝謝:)

回答

0
import os 
from os.path import join, getsize 

def size_list(mypath): 
    with open("PathTest.txt","w") as of: 
     for root, dirs, files in os.walk(mypath): 
      for f in files: 
       fo.write("\nPath: " + os.path.join(root, f)) 
       fo.write("\tSize: " + str(getsize(os.path.join(root, f))) + " bytes") 

size_list("path/to/dir") 

的數據結構,你可以使用(路徑,大小)的元組的名單爲:

def size_list(mypath): 
    my_list = [] 
    with open("PathTest.txt","w") as of: 
     for root, dirs, files in os.walk(mypath): 
      for f in files: 
       my_file = os.path.join(root, f) 
       file_size = getsize(my_file) 
       my_list.append((my_file, file_size)) 
       fo.write("\nPath: " + my_file) 
       fo.write("\tSize: " + str(file_size) + " bytes") 
+0

路徑/ DIR用於/以追加的路徑? – LunaLove