在CSV文件新增行时写入当前日期遇TypeError报错求助
解决CSV写入时的TypeError问题
问题原因
报错TypeError: 'datetime.date' object is not iterable是因为zip()函数会尝试迭代传入的每个参数,但today = date.today()得到的是单个datetime.date对象,它不属于可迭代类型,无法被zip正常处理。
修复方案
- 将日期包装为可迭代对象
把单个日期对象放到列表或元组里,让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,),效果完全一致。
- 可选:格式化日期为字符串
如果需要自定义日期格式(比如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
相关产品推荐
相关产品推荐

