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

在CSV文件新增行时写入当前日期遇TypeError报错求助

解决CSV写入时的TypeError问题

问题原因

报错TypeError: 'datetime.date' object is not iterable是因为zip()函数会尝试迭代传入的每个参数,但today = date.today()得到的是单个datetime.date对象,它不属于可迭代类型,无法被zip正常处理。

修复方案

  1. 将日期包装为可迭代对象
    把单个日期对象放到列表或元组里,让zip()可以正常迭代:
from datetime import date
import csv

today = date.today()
with open('data6.csv', 'a') as storage_file:
    writer = csv.writer(storage_file)
    # 用[today]将日期包装成可迭代的列表
    writer.writerows(zip(username, password, ip_address, ticket, [today]))
    # with语句会自动关闭文件,无需手动调用close()

也可以用元组形式(today,),效果完全一致。

  1. 可选:格式化日期为字符串
    如果需要自定义日期格式(比如2024/05/20),可以先把日期转成指定格式的字符串再包装:
from datetime import date
import csv

today_str = date.today().strftime('%Y/%m/%d')  # 自定义日期格式
with open('data6.csv', 'a') as storage_file:
    writer = csv.writer(storage_file)
    writer.writerows(zip(username, password, ip_address, ticket, [today_str]))

额外优化

删除手动的storage_file.close():with上下文管理器会在代码块执行完毕后自动关闭文件,手动调用反而可能引发不必要的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 16:02:02