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

pandas调用to_csv存储文件报OSError Errno 22无效参数问题咨询

错误根因

你遇到的OSError: [Errno 22] Invalid argument报错是因为Windows系统对文件名包含非法字符导致:Windows禁止文件名中出现:、<、>、/等特殊字符,你使用datetime.utcnow().isoformat()生成的时间戳格式为2021-10-08T10:56:27.991570,其中时分秒之间的:属于非法字符,拼接到文件路径后被系统拦截。
你之前的修改操作(改斜杠、升级pandas、改路径)都没有命中问题根源,因此无效。

修复方案

  • 方案1:直接替换时间戳中的冒号为合法字符,示例代码:
timestamp = datetime.utcnow().isoformat().replace(':', '-')

替换后生成的时间戳格式为2021-10-08T10-56-27.991570,符合Windows文件命名规则。

  • 方案2:自定义时间格式化规则,直接生成不含非法字符的时间串,可灵活调整时间精度:
# 格式为 年-月-日T时-分-秒.微秒
timestamp = datetime.utcnow().strftime("%Y-%m-%dT%H-%M-%S.%f")
# 不需要微秒可以调整为
# timestamp = datetime.utcnow().strftime("%Y-%m-%dT%H-%M-%S")

修改后完整函数示例

def write_to_csv(dataframe, filename):
    timestamp = datetime.utcnow().isoformat().replace(':', '-')
    dataframe.to_csv(fr'C:/Users/freddie.bazanye-lutu/BBDS_Repo/Scripts/{filename}-{timestamp}.csv', index=False, header=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 15:33:00