递归累计文件内容

时间:2017-05-27 11:49:34

标签: python recursion

我正在尝试编写一个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

2 个答案:

答案 0 :(得分:1)

您根本没有生成文件路径。您需要将文件名与当前路径连接才能获取文件路径,然后才能获得相关文件的大小:

button.clipsToBounds = true

答案 1 :(得分:-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")

试试这个!