我想寫一個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
目錄下運行:
所以,你幾乎在做'du'的功能呢?也許只是使用'du'? –
您只打印目錄大小。目錄的大小不考慮內容。 – user1620443
另外,你有沒有注意到你只添加了最後一次迭代的結果? – user1620443