首页  >  文章  >  后端开发  >  如何在Python中递归遍历文件夹结构来读取文本文件内容?

如何在Python中递归遍历文件夹结构来读取文本文件内容?

Patricia Arquette
Patricia Arquette原创
2024-10-18 14:36:44678浏览

How to Recursively Traverse a Folder Structure to Read Text File Contents in Python?

Python 递归文件夹读取:克服浅层探索

在编程领域,有效地导航复杂的层次结构通常具有挑战性。对于具有 C /Obj-C 背景的初露头角的 Python 爱好者来说,递归遍历文件夹结构来读取文本文件的内容可能会造成巨大的障碍。

让我们深入研究您提供的代码,以了解限制它的递归超出了单个文件夹深度:

<code class="python">import os
import sys

rootdir = sys.argv[1]

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

    for folder in subFolders:
        outfileName = rootdir + "/" + folder + "/py-outfile.txt" # hardcoded path
        folderOut = open( outfileName, 'w' )
        print "outfileName is " + outfileName

        for file in files:
            filePath = rootdir + '/' + file
            f = open( filePath, 'r' )
            toWrite = f.read()
            print "Writing '" + toWrite + "' to" + filePath
            folderOut.write( toWrite )
            f.close()

        folderOut.close()</code>

罪魁祸首在于 filePath 的硬编码路径:

<code class="python">filePath = rootdir + '/' + file</code>

此代码假定一个文件夹的固定深度,从而阻止其正确执行提取嵌套文件夹中的文件路径。为了解决这个问题,我们需要合并当前的根值,它提供了当前迭代文件夹的路径:

<code class="python">filePath = os.path.join(root, file)</code>

通过利用 os.path.join,我们构建了一个准确的完整文件路径,允许成功探索文件夹结构的所有级别的代码。

此外,谨慎使用 with 语句来处理文件操作,这可以确保文件自动关闭,增强代码可读性并减少潜在的资源泄漏。

这是解决这些问题的代码修订版本:

<code class="python">import os
import sys

walk_dir = sys.argv[1]

print('walk_dir = ' + walk_dir)

# Converting to absolute path ensures portability
walk_dir = os.path.abspath(walk_dir)
print('walk_dir (absolute) = ' + 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')</code>

通过这些修改,您的 Python 代码将

以上是如何在Python中递归遍历文件夹结构来读取文本文件内容?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn