2017-05-27 37 views
0

我想寫一個Python腳本,將一個目錄作爲輸入,並遞歸地查看該目錄並將文件名和它們的大小輸出到一個文件。最後,它彙總了整個目錄。輸出是好的,適合我所需要的,但是當我在/var目錄上運行此代碼時,所有文件大小都列在4096處。下面是代碼:遞歸總計文件內容

#!/usr/bin/python 
import os 

#print usage for input directory and accepts input 

print("Example: /home/cn") 
input_file = raw_input("Enter the name of the directory: ") 

#prints usage for output file and accepts input 

print("Example: /home/cn/Desktop/output_test.txt") 
output_file = raw_input("Enter the name of the output file: ") 

#opens output file for writing, sets variable for directory size to 0 

of = open(output_file, "w") 
start_path = input_file 
total_size = 0 

#loops recursively, calculates directory size 

for (path,dirs,files) in os.walk(start_path): 
    of.write(format(path)) 
    of.write(" " + str(os.path.getsize(path)) + "\n") 
    for file in files: 
     fstat=os.stat(os.path.join(path,file)) 
     size = os.stat(path).st_size 
     total_size = total_size + size 

#writes output to file 

of.write("\n" + "Directory: " + input_file + "\n") 
of.write("The total size of the directory is: " + str(total_size)) 

而且還輸出文件的截圖時,此點在/var目錄下運行:

/var directory output

+0

所以,你幾乎在做'du'的功能呢?也許只是使用'du'? –

+0

您只打印目錄大小。目錄的大小不考慮內容。 – user1620443

+0

另外,你有沒有注意到你只添加了最後一次迭代的結果? – user1620443

回答

1

根本沒有生成文件路徑。您需要將當前路徑加入文件名以獲取文件路徑,然後才能獲得有問題文件的大小:

for path, dirs, files in os.walk(start_path): 
    full_path = os.path.abspath(os.path.realpath(path)) # just to cover symlinks 
    of.write("{} {}\n".format(full_path, os.path.getsize(full_path))) # not a real size! 
    for file in files: 
     file_path = os.path.join(full_path, file) # get the file path 
     size = os.stat(file_path).st_size # get the actual file stats 
     of.write(" {} {}\n".format(file_path, size)) # write the file path and size 
     total_size += size 
+0

在內部循環中,應該是file_path,而不是full_path,要打印 – user1620443

+0

是的 - 這解決了它。非常感謝。 – itsalittleguy

-2

那是因爲你只是檢查根路徑大小。

而是嘗試下面的代碼

for (path,dirs,files) in os.walk(start_path): 
    of.write(format(path)) 
    of.write(" " + str(os.path.getsize(path)) + "\n") 
    for dir in dirs: 
     dir_path = os.path.join(path, dir) 
     of.write(format(dir_path)) 
     of.write(" " + str(os.path.getsize(dir_path)) + "\n") 

試試這個!

+0

這並沒有列出這些文件,而是列出了目錄,所以它不會執行OP所需的任何操作,而且從目錄中獲取大小會使您獲得目錄的大小記錄,而不是目錄內容的大小。最後,你不會在最後的'total_size'中添加任何東西,因此無論如何統計數據都會返回'0'。 – zwer

+0

根是路徑。忘記改變真實的代碼。 –