Python脚本遍历嵌套文件夹处理图片时os.walk报错,寻求解决帮助
Hey there! The issue you're hitting makes total sense—os.walk churns through every item in your directory structure, including folders themselves, and your script is probably trying to run image-specific logic (like XMP embedding or regex filename changes) on those folder paths, which causes errors. Let's fix this step by step.
Core Fix: Separate Files from Folders
The key is to add checks in your os.walk loop to only process actual image files, not directories. Here's how to adjust your script:
- Define which file types are images: List out the extensions you care about (adjust based on your needs).
- Filter files in the walk loop: For each item returned by
os.walk, verify it's a file and has an image extension before processing. - Use full file paths:
os.walkgives you the root directory and filename separately—combine them to get the complete path to the image.
Example Adjusted Code
Let's say your existing image processing logic is wrapped in a function called process_single_image(file_path). Here's how to integrate it with os.walk:
import os def process_single_image(file_path): # Your existing logic here: # 1. Embed XMP data # 2. Modify filename with regex # 3. Move the file print(f"Processing: {file_path}") # Define image extensions to target (add/remove as needed) IMAGE_EXTENSIONS = ('.jpg', '.jpeg', '.png', '.tiff', '.webp') # Start walking from your target directory target_dir = "/path/to/your/root/folder" for root, dirs, files in os.walk(target_dir): for filename in files: # Get the full path to the file full_path = os.path.join(root, filename) # Skip if it's not a file (just a safeguard, though files should be files here) if not os.path.isfile(full_path): continue # Check if the file has an image extension (case-insensitive) file_ext = os.path.splitext(filename)[1].lower() if file_ext in IMAGE_EXTENSIONS: # Run your processing logic process_single_image(full_path)
Key Notes to Avoid Headaches
- Case-insensitive extensions: By converting the extension to lowercase, you'll catch files named
IMAGE.JPGorphoto.PNGwithout missing them. - Skip directories explicitly: Even though
filesfromos.walkshould only be files, addingos.path.isfile()is a safe guard against edge cases (like symbolic links that point to directories). - Test with a small folder first: Before running on your full directory, test with a nested folder structure to make sure it's processing only images and not throwing errors.
If you're still hitting specific errors (like regex matching issues on certain filenames), feel free to share the exact error message and a snippet of your regex logic—I can help tweak that too!
内容的提问来源于stack exchange,提问作者Richard

