python3 遍历文件夹目录所有文件
Posted Woowo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python3 遍历文件夹目录所有文件相关的知识,希望对你有一定的参考价值。
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 = ‘{} {} ‘.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 = ‘{}:{}:{} ‘.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)
以上是关于python3 遍历文件夹目录所有文件的主要内容,如果未能解决你的问题,请参考以下文章