软件测试职业探索

Python学习练手小项目:遍历指定路径下的所有文件(包括子目录

2019-10-08  本文已影响0人  R_zb

1、准备测试数据

E:\测试文件夹
│  haha.xlsx
│  test.rar
│  哈哈.txt
│  
├─测试1
│  │  1.txt
│  │  111.rtf
│  │  
│  ├─1
│  │      1111.txt
│  │      
│  └─2
├─测试2
└─测试3
        哈哈.txt
        

注:目录树生成:https://www.jianshu.com/p/7f20dffa7c79

2、测试代码

# 用于遍历指定路径内,删选符合要求文件数据
def walk_dir(path):
    count = 0
    if os.path.exists(path) == True:
        for root, dirs, files in os.walk(path):
            for item in files:
                if '.txt' in item:
                    # os.remove(os.path.join(root, item))
                    # print('已删除文件:%s' % item)
                    count += 1
                else:
                    pass
        print("txt文件共:%d个" % count)
    else:
        print('输入路径不存在')


if __name__ == '__main__':
    path = r'E:\测试文件夹'
    walk_dir(path)

3、测试结果

测试结果.png

Blog:

上一篇 下一篇

猜你喜欢

热点阅读