编程语言
首页 > 编程语言> > Python.遍历目标路径下所有

Python.遍历目标路径下所有

作者:互联网

import stat
from tkinter.filedialog import *


def traversal_dir(dir_name):
    rets = []
    try:
        if len(dir_name):
            for r, ds, fs in os.walk(dir_name):
                for i1 in fs:
                    rets.append(str(os.path.join(r, i1)).replace('\\', '/'))
                for i2 in ds:
                    rets.append(str(os.path.join(r, i2)).replace('\\', '/'))
    except Exception as e:
        print(e)
    return rets


if __name__ == '__main__':
    try:
        pass  # 1,选择目标路径
        strDirPath = askdirectory()
        if len(strDirPath):
            pass  # 2,遍历目标路径下所有
            paths = traversal_dir(strDirPath)
            with open('temp.txt', 'w', encoding='utf8') as f:
                for path in paths:
                    f.write(path + '\n')
            os.system('temp.txt')
            os.chmod('temp.txt', stat.S_IWRITE)  # 剔除只读属性
            os.remove('temp.txt')
        pass
    except Exception as e:
        print(e)

标签:__,遍历,Python,路径,rets,path,txt,os,dir
来源: https://www.cnblogs.com/dailycode/p/12459781.html