dic = {
‘sum_size‘:0,
‘file_num‘:0,
‘directory_num‘:0
}
def get_size(path,txt):
items =os.listdir(path)
files = []
dirs = []
sum_size = 0
for item in items:
item = os.path.join(path,item)
if os.path.isdir(item):
dirs.append(item)
elif os.path.isfile(item):
files.append(item)
for file in files:
size = os.path.getsize(file)
sum_size += size
print(file,size)
dic[‘file_num‘] += 1
dic[‘sum_size‘] += size
with open(txt,mode="a+",encoding=‘utf-8‘) as f:
data = ‘{} {}\n‘.format(file,size)
f.write(data)
for directory in dirs:
dic[‘directory_num‘] += 1
# sum_size += get_size(directory,txt)
get_size(directory, txt)
return dic[‘sum_size‘]
if __name__ == ‘__main__‘:
path = ‘E:\IDMD‘
txt = ‘data.txt‘
# result = get_size(path,txt)
# print(result)
get_size(path, txt)
data = ‘{}:{}:{}\n‘.format(dic[‘directory_num‘], dic[‘file_num‘], dic[‘sum_size‘])
print(data)
with open(txt, mode="a+",encoding=‘utf-8‘) as f:
f.write(data)
原文:https://www.cnblogs.com/kuraki/p/9797919.html