您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python递归文件夹读取

Python递归文件夹读取

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

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

具有以下含义:

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

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

import os
import sys

walk_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).encode('utf-8'))
                list_file.write(f_content)
                list_file.write(b'\n')

如果您不知道,则with文件声明是一种简写形式:

with open('filename', 'rb') as f:
    dosomething()

# is effectively the same as

f = open('filename', 'rb')
try:
    dosomething()
finally:
    f.close()
python 2022/1/1 18:35:22 有234人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶