Python中Image对象保存TIFF图像失败,报AttributeError求助
Hey there, let's break down why your save() method is throwing an AttributeError and how to fix it!
The Root Cause
Looking at your code, the issue is straightforward: you're passing lists to the save() method instead of a string file path. PIL's Image.save() expects the first argument to be a string representing the full file path (including the file extension, ideally), but your path and mask_path variables are lists like ['../data/', '5'] (assuming i-10 equals 5). When PIL tries to work with this list as a path, it throws an AttributeError because lists don't have the attributes it needs to handle file operations.
The Fix
You need to convert those list paths into proper strings. Here are a few clean ways to do this:
Using f-strings (Python 3.6+): This is the most readable approach:
# Build full string paths with .tiff extension path = f'../data/{i-10}.tiff' mask_path = f'../data/{i-10}_mask.tiff'String concatenation: If you prefer older syntax:
path = '../data/' + str(i-10) + '.tiff' mask_path = '../data/' + str(i-10) + '_mask.tiff'Joining the list: If you want to keep using the list structure for some reason:
path_parts = ['../data/', str(i-10), '.tiff'] path = ''.join(path_parts) mask_path_parts = ['../data/', str(i-10), '_mask.tiff'] mask_path = ''.join(mask_path_parts)
Full Corrected Code
Here's how your code should look after the fix:
from PIL import Image import os # Make sure the target directory exists (prevents "file not found" errors) os.makedirs('../data/', exist_ok=True) # Build proper string paths path = f'../data/{i-10}.tiff' mask_path = f'../data/{i-10}_mask.tiff' collage = Image.fromarray(collage, 'L') collage_mask = Image.fromarray(collage_mask, '1') collage.save(path, 'tiff') collage_mask.save(mask_path, 'tiff')
Extra Tip:
Adding os.makedirs('../data/', exist_ok=True) ensures the ../data/ directory exists before trying to save files there. Without this, you might get a FileNotFoundError if the directory hasn't been created yet.
内容的提问来源于stack exchange,提问作者Jonathan

