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>
Here's a breakdown of the improved 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!