You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中Image对象保存TIFF图像失败,报AttributeError求助

Fixing AttributeError When Saving PIL Image as TIFF

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:

  1. 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'
    
  2. String concatenation: If you prefer older syntax:

    path = '../data/' + str(i-10) + '.tiff'
    mask_path = '../data/' + str(i-10) + '_mask.tiff'
    
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:26:35