栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python递归文件夹读取

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python递归文件夹读取

确保您了解以下三个返回值

os.walk

for root, subdirs, files in os.walk(rootdir):

具有以下含义:

  • root
    :“经过”的当前路径
  • subdirs
    root
    目录类型中的文件
  • files
    :目录以外的其他文件
    root
    (不在中
    subdirs

并且请使用

os.path.join
而不是用斜杠连接!您的问题是
filePath = rootdir + '/' +file
-您必须串联当前的“移动”文件夹,而不是最顶层的文件夹。所以一定是
filePath = os.path.join(root,file)
。顺便说一句,“文件”是内置的,因此通常不将其用作变量名。

另一个问题是您的循环,例如:

import osimport syswalk_dir = sys.argv[1]print('walk_dir = ' + walk_dir)# If your current working directory may change during script execution, it's recommended to# immediately convert program arguments to an absolute path. Then the variable root below will# be an absolute path as well. Example:# walk_dir = os.path.abspath(walk_dir)print('walk_dir (absolute) = ' + os.path.abspath(walk_dir))for root, subdirs, files in os.walk(walk_dir):    print('--nroot = ' + root)    list_file_path = os.path.join(root, 'my-directory-list.txt')    print('list_file_path = ' + list_file_path)    with open(list_file_path, 'wb') as list_file:        for subdir in subdirs: print('t- subdirectory ' + subdir)        for filename in files: file_path = os.path.join(root, filename) print('t- file %s (full path: %s)' % (filename, file_path)) with open(file_path, 'rb') as f:     f_content = f.read()     list_file.write(('The file %s contains:n' % filename).enpre('utf-8'))     list_file.write(f_content)     list_file.write(b'n')

如果您不知道,则

with
文件声明是一种简写形式:

with open('filename', 'rb') as f:    dosomething()# is effectively the same asf = open('filename', 'rb')try:    dosomething()finally:    f.close()


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/645701.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号