遍历目录获取目录及子目录下的所有文件及对应文件大小
# -*- coding: utf-8 -*-
# @Time : 2021/7/28 下午2:28
# @Author : lizhichao
# @File : traverse_Recursion.py
# @Software: PyCharm
import os
import sys
def traverse_recursion(dirctory,ouputfile):
"""
:param dirctory: the need to be traversed directory
:param ouputfile: All the file and corresponding file size
"""
content=""
for root,dirs,files in os.walk(dirctory):
for file in files:
file_path=os.path.join(root,file)
filesize=round((os.path.getsize(file_path))/float(1024*1024),2)
content+="%s\t%s\n"%(file_path,filesize) #store the files of present root
with open(ouputfile,"w") as f:
f.write(content)
if __name__=="__main__":
dirctory=sys.argv[1]
outfile=sys.argv[2]
traverse_recursion(dirctory,outfile)
>核心调用:
for root,dirs,files in os.walk(dirctory): #每次遍历对象,都返回三元组:
root 当前正在遍历的目录路径
dirs 是当前遍历目录下所有目录的名称,是一个list。不包括子目录
files 是当前目录下所有文件。不包括子目录。
#默认os.walk(topdown=True)为真,先遍历dirctory,再遍历子目录,如此循环。