【发布时间】:2017-11-16 22:42:42
【问题描述】:
以下代码为我提供了所有文件夹、子文件夹和文件的数据以及每个文件的大小。目前,这是将数据保存在 CSV 文件中。但我相信这种数据(嵌套数据)最适合 XML。我不太精通 XML。任何修改代码的帮助将不胜感激
import os
import csv
def GetHumanReadable(size,precision=2):
suffixes=['KB','MB','GB','TB']
suffixIndex = 0
while size > 1024:
suffixIndex += 1 #increment the index of the suffix
size = size/1024.0 #apply the division
return "%.*f %s"%(precision,size,suffixes[suffixIndex])
def list_files(startpath):
with open('output.csv','w') as file:
for root, dirs, files in os.walk(startpath):
level = root.replace(startpath, '').count(os.sep)
indent = ' ,' * 4 * (level)
file.write('{}{}/\n'.format(indent, os.path.basename(root)))
subindent = ' ,' * 4 * (level + 1)
for f in sorted(files, key=lambda f: os.path.getsize(root + os.sep + f)):
converted_size = GetHumanReadable(os.path.getsize(root + os.sep + f))
file.write('{}{},{}\n'.format(subindent, f, converted_size))
【问题讨论】: