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

如何在Python保存图片时同步将文件名逐行写入文本文件?

Python保存图片同时记录文件名到文本文件

很简单,只需要在你现有代码的基础上,增加一段写入文本文件的逻辑就行。我给你调整好的完整代码,还补全了必要的导入语句:

import os
import uuid

def save_image(raw_image, image_type, save_directory, log_file="image_filenames.txt"):
    # 处理文件扩展名,为空则默认用jpg
    extension = image_type if image_type else 'jpg'
    # 生成唯一的随机文件名
    file_name = str(uuid.uuid4().hex) + "." + extension
    # 拼接完整的图片保存路径
    save_path = os.path.join(save_directory, file_name)
    
    # 写入图片文件
    with open(save_path, 'wb+') as image_file:
        image_file.write(raw_image)
    
    # 将文件名追加到文本日志中(用utf-8编码避免乱码)
    log_full_path = os.path.join(save_directory, log_file)
    with open(log_full_path, 'a', encoding='utf-8') as log_f:
        log_f.write(file_name + '\n')
    
    # 可选返回文件名,方便后续业务逻辑调用
    return file_name

几个细节说明:

  • 新增了log_file可选参数,默认会在图片保存的文件夹下生成image_filenames.txt,你也可以传入自定义的文件路径或名称
  • 用'a'(追加模式)打开日志文件,每次保存图片都会把新文件名加到文件末尾,不会覆盖之前的记录
  • 给日志文件指定了utf-8编码,避免不同系统下出现文件名乱码的问题

内容的提问来源于stack exchange,提问作者user9619272

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:11:50