【Python】遍历文件夹中所有文件

来源:互联网 发布:adobe xd for mac 编辑:程序博客网 时间:2024/06/05 23:02

http://blog.csdn.net/u012866328/article/details/53007474


一个小递归函数:遍历文件夹中所有的文件,返回值(路径)包含扩展名


import osimport sys'''    扫描文件夹dir中所有文件,返回文件的相对路径列表'''def GetFileList(dir, fileList):    newDir = dir    if os.path.isfile(dir):         # 如果是文件则添加进 fileList        fileList.append(dir)    elif os.path.isdir(dir):        for s in os.listdir(dir):   # 如果是文件夹            newDir = os.path.join(dir, s)            GetFileList(newDir, fileList)    return fileList# 主函数# 重定向输出位置output = sys.stdoutoutputfile = open('test.txt', 'w')sys.stdout = outputfilelist = GetFileList('myFolder', []) # 获取所有myFolder文件夹下所有文件名称(包含拓展名)# 输出所有文件夹中的路径(相对于当前运行的.py文件的相对路径)for route in list:    # route 为路径    print(route)# 关闭输出重定向outputfile.close()sys.stdout = output
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34