如何用Python批量转换文件夹中全部BMP图像为PPM格式?
Fixing Batch BMP to PPM Conversion with Python PIL
Hey there! Let's sort out why your code is only converting a single image and tweak it to handle every BMP in your target folder.
The Issue in Your Current Code
Looking at your snippet, you defined a directory variable but never actually used it. The glob.glob("*.bmp") call only searches for BMP files in your current working directory (the folder you run the script from), not the folder you specified. That's why only one (if any) image is getting converted if your BMPs are stored elsewhere.
Fixed Batch Conversion Code
Here's the adjusted code that will process every BMP in your target directory (and subfolders too, if you want):
from PIL import Image import glob import os # Replace this with your actual folder path directory = "your/path/here" # Use os.path.join to build cross-platform file paths # Set recursive=True if you want to include BMPs in subfolders for infile in glob.glob(os.path.join(directory, "*.bmp"), recursive=False): # Split the full file path to keep the original location for the PPM file_path, ext = os.path.splitext(infile) # Use a context manager to auto-close the image after saving with Image.open(infile) as im: im.save(f"{file_path}.ppm", "PPM") # Optional: Track progress in the console print(f"Converted: {os.path.basename(infile)} -> {os.path.basename(file_path)}.ppm")
Key Improvements Explained
- Leveraging your target directory:
os.path.join(directory, "*.bmp")ensures we're searching exactly where your BMPs are stored, not just the script's default folder. - Cross-platform compatibility:
os.path.joinbuilds paths correctly on Windows, Mac, and Linux—no more messing with forward/backward slashes. - Cleaner file handling: The
withstatement automatically closes the image after saving, preventing unnecessary resource usage. - Progress tracking: The print statement lets you see which files are being processed, helpful for larger folders.
Quick Tips
- Make sure Pillow is installed: Run
pip install pillowif you haven't already. - To convert BMPs in subfolders, just change
recursive=Falsetorecursive=True. - On Windows, use a raw string for your directory path (like
r"C:\Your\BMP\Folder") to avoid escape character errors.
内容的提问来源于stack exchange,提问作者Chinmaya Urs
相关产品推荐
相关产品推荐

