python分析代码02

import os#导入os包
result = []#设置一个空列表
def get_all(cwd):
    get_dir = os.listdir(cwd)  #遍历当前目录,获取文件列表名
    for i in get_dir:    #遍历get_dir文件
        sub_dir = os.path.join(cwd,i)  # 获取的文件加入路径,也就是把cwd路径和i路径组合起来,也就组成了一个完整的路径

        if os.path.isdir(sub_dir):     #如果当前仍然是文件夹
            get_all(sub_dir)#自己调用自己,递归
        else:
            ax = os.path.basename(sub_dir)  #因为sub_dir是一个完整的路径,这条命令是获取路径中的最后的名字,也就是获取文件名
            result.append(ax)#把文件名添加到result列表中
            print(len(result))   #对列表计数
            
if __name__ == "__main__":    #相当于一个程序的入口
    cur_path = os.getcwd()   #os.getcwd用于返回当前目录
    get_all(cur_path)#调用函数

#os.path模块主要用于文件的属性获取https://www.cnblogs.com/wuxie1989/p/5623435.html

猜你喜欢

转载自blog.csdn.net/qq_37181884/article/details/81194669