How to Recursively Read Files and Write Content in Python Folders?

Barbara Streisand
Release: 2024-10-18 14:39:02
Original
535 people have browsed it

How to Recursively Read Files and Write Content in Python Folders?

Recursive Folder Reading in Python

In Python, OS operations like finding directories and files can be done with the os module. To recursively read content from files within a folder structure, we can utilize os.walk.

The snippet below illustrates how you can recursively explore a folder and its subdirectories, opening text files to read their contents:

<code class="python">import os

def read_folder_recursively(rootdir):
    for root, subdirs, files in os.walk(rootdir):
        for folder in subdirs:
            # Define the output file path within the current subfolder
            outfileName = os.path.join(root, folder, "py-outfile.txt")
            with open(outfileName, 'w') as folderOut:
                print("outfileName is " + outfileName)
                for file in files:
                    filePath = os.path.join(root, file)
                    with open(filePath, 'r') as f:
                        toWrite = f.read()
                        print("Writing '" + toWrite + "' to" + filePath)
                        folderOut.write(toWrite)
                    f.close()
            folderOut.close()</code>
Copy after login

Here's a breakdown of the improved code:

  • Use os.path.join to concatenate paths instead of string addition.
  • Open files using the with statement for proper file handling.
  • Ensure proper indentation and variable names to maintain code readability.
  • Eliminate unnecessary loops that were causing issues in the initial code.

This updated code correctly handles multiple folder depths, dynamically creates output files within each subfolder, and effectively writes content from text files into the output files.

The above is the detailed content of How to Recursively Read Files and Write Content in Python Folders?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!