首頁 >後端開發 >Python教學 >如何在Python中遞歸讀取超過一級子目錄的資料夾內容?

如何在Python中遞歸讀取超過一級子目錄的資料夾內容?

Barbara Streisand
Barbara Streisand原創
2024-10-18 14:42:03850瀏覽

How to Recursively Read Folder Contents Beyond One Subdirectory Level in Python?

Python Recursive Folder Read

This question arises when working with a Python script to recursively read the contents of text files in a folder structure. However, the initial code provided encountered a limitation of reading only one folder deep.

Problem Identification

The issue lies in the hardcoded path: outfileName = rootdir + "/" + folder + "/py-outfile.txt". This path assumes that the target file is located one subfolder below the root directory.

Solution

To address this limitation, we need to understand the return values of os.walk:

  • root: The current path being processed.
  • subdirs: A list of subdirectories in root.
  • files: A list of non-directory files in root.

Instead of using filePath = rootdir + '/' + file, we should utilize os.path.join to combine root and file: filePath = os.path.join(root, file). This approach allows us to correctly navigate through the folder hierarchy.

Revised Code

Here's a revised version of the code:

import os
import sys

walk_dir = sys.argv[1]

print('walk_dir = ' + walk_dir)

# Convert to absolute path (recommended if the working directory may change during execution)
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')

This revised code will now recursively traverse the entire folder structure and write the contents of each file to the specified list_file_path.

以上是如何在Python中遞歸讀取超過一級子目錄的資料夾內容?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn