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

如何在os.getcwd()前添加r前缀以规避OSError: [Errno 22]无效参数错误?

解决OSError: [Errno 22] Invalid argument 文件路径问题

你的OSError: [Errno 22] Invalid argument是手动拼接文件路径时的格式错误导致的——手动用\\拼接容易出现转义字符干扰路径解析的问题。给路径加r前缀(原始字符串)能解决转义问题,但更稳妥的是用Python内置路径工具彻底规避拼接错误。

原始错误代码

# write data file
with open(os.getcwd() + '\\' + infile, 'wb') as f:
    n, d = X.shape
    f.write(struct.pack("=i", n))
    f.write(struct.pack("=i", d))
    f.write(struct.pack("=d", theta))
    f.write(struct.pack("=d", perplexity))

修改方案1:使用os.path.join(推荐)

os.path.join会自动适配Windows/macOS/Linux的路径分隔符,完全避免手动拼接的错误:

# write data file
import os
import struct

with open(os.path.join(os.getcwd(), infile), 'wb') as f:
    n, d = X.shape
    f.write(struct.pack("=i", n))
    f.write(struct.pack("=i", d))
    f.write(struct.pack("=d", theta))
    f.write(struct.pack("=d", perplexity))

修改方案2:使用原始字符串

如果坚持手动拼接,给路径字符串加r前缀,让Python按原始字符解析路径:

# write data file
with open(r"{}\{}".format(os.getcwd(), infile), 'wb') as f:
    n, d = X.shape
    f.write(struct.pack("=i", n))
    f.write(struct.pack("=i", d))
    f.write(struct.pack("=d", theta))
    f.write(struct.pack("=d", perplexity))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 18:40:32