Python三级文件夹层级创建脚本求助:已完成一级文件夹生成
Hey there! Nice work getting the first part of your script up and running. Let's tweak it to add that consistent 3-level subdirectory structure under each main folder you create.
First, let's clean up your existing code a bit (fixing that incomplete print statement and using safer path handling) and then add the subdirectory logic. Here's how to do it:
Step 1: Define Your Subdirectory Structure
First, decide what your 3-level structure should look like. For example, if you want each main folder to have data/raw/archives, docs/reports/weekly, or any other structure, define it as a list of relative paths. Let's use a sample structure for this example:
# Define your 3-level subdirectory paths (relative to each main folder) subdir_structure = [ "level1", "level1/level2", "level1/level2/level3" ]
You can adjust these paths to match your actual needs.
Step 2: Full Updated Script
Here's the complete script that combines your original folder creation with the nested subdirectories:
from sys import argv import os home_dir = '/home/tobi/Python' # Define your 3-level subdirectory structure subdir_structure = [ "level1", "level1/level2", "level1/level2/level3" ] # Use a 'with' statement to safely open and close the file with open('test.txt', 'r') as mylist: for folder in mylist: folder = folder.strip() # Skip empty lines in the text file if not folder: continue # Create the main folder path main_folder_path = os.path.join(home_dir, folder) # Create the main folder (ignore if it already exists) os.makedirs(main_folder_path, exist_ok=True) print "Created main folder: {}".format(main_folder_path) # Now create each subdirectory in the structure for subdir_rel_path in subdir_structure: subdir_full_path = os.path.join(main_folder_path, subdir_rel_path) os.makedirs(subdir_full_path, exist_ok=True) print "Created subdirectory: {}".format(subdir_full_path)
Key Improvements & Explanations:
- Using
os.path.join: This is safer than manually concatenating paths with/because it handles different operating system path separators automatically (works on Windows, macOS, Linux). withstatement for file handling: Automatically closes the text file after reading, which is better practice than leaving it open.exist_ok=Trueinos.makedirs: Prevents errors if a folder or subdirectory already exists (the function will just skip creating it instead of throwing an exception).- Skipping empty lines: Checks if the line from
test.txtis empty and skips it, so you don't create folders with blank names.
Quick Note for Python 3 Users:
If you're running Python 3 instead of 2, just wrap the print arguments in parentheses (e.g., print("Created main folder: {}".format(main_folder_path))) to match the function syntax.
That's it! Run this script, and each main folder from test.txt will have your specified 3-level subdirectory structure.
内容的提问来源于stack exchange,提问作者Tobias Heini

