如何批量复制多级目录下的speed_vs_time.png并重命名归档?
Hey there! Let's sort out this batch file copying and renaming task for you. Below are a couple of straightforward, cross-platform or OS-specific approaches to get this done quickly:
Method 1: Command Line (OS-Specific)
For Linux/macOS (Bash)
- First, navigate to your
Main_directory:cd /path/to/your/Main_directory - Create the target
imagesfolder (if it doesn't exist already):mkdir -p images - Run this loop to copy and rename the files:
for dir in */; do # Define the source file path src_file="${dir}case1/results/speed_vs_time.png" # Check if the source file exists before proceeding if [ -f "$src_file" ]; then # Extract the folder name (remove trailing slash) folder_name="${dir%/}" # Copy and rename the file to the images folder cp "$src_file" "images/${folder_name}.png" echo "Copied $src_file to images/${folder_name}.png" else echo "Warning: $src_file does not exist, skipping folder $dir" fi done
For Windows (PowerShell)
- Navigate to your
Main_directory:Set-Location -Path "C:\path\to\your\Main_directory" - Create the
imagesfolder (with-Forceto avoid errors if it exists):New-Item -ItemType Directory -Name "images" -Force - Execute this loop to handle the files:
Get-ChildItem -Directory | ForEach-Object { $srcPath = Join-Path -Path $_.FullName -ChildPath "case1\results\speed_vs_time.png" # Verify the source file exists if (Test-Path -Path $srcPath -PathType Leaf) { $destPath = Join-Path -Path "images" -ChildPath "$($_.Name).png" Copy-Item -Path $srcPath -Destination $destPath -Force Write-Host "Copied $srcPath to $destPath" } else { Write-Warning "$srcPath not found, skipping folder $($_.Name)" } }
Method 2: Cross-Platform Python Script
If you prefer a script that works on any OS (as long as Python is installed), use this:
import os import shutil # Replace this path with your actual Main_directory path main_dir = "/path/to/your/Main_directory" # For Windows: "C:\\path\\to\\your\\Main_directory" images_dir = os.path.join(main_dir, "images") # Create the images folder if it doesn't exist os.makedirs(images_dir, exist_ok=True) # Loop through each subfolder in Main_directory for folder_name in os.listdir(main_dir): folder_path = os.path.join(main_dir, folder_name) # Only process actual directories if os.path.isdir(folder_path): src_file = os.path.join(folder_path, "case1", "results", "speed_vs_time.png") if os.path.isfile(src_file): dest_file = os.path.join(images_dir, f"{folder_name}.png") # Use copy2 to preserve file metadata like creation date shutil.copy2(src_file, dest_file) print(f"Successfully copied: {src_file} -> {dest_file}") else: print(f"Warning: {src_file} does not exist, skipping {folder_name}")
To use this script:
- Replace the
main_dirpath with your actual directory path - Save the file as
copy_images.py - Run it with
python copy_images.py
内容的提问来源于stack exchange,提问作者Programming
相关产品推荐
相关产品推荐

