OSError: [Errno 22] Invalid argument: file path

发布时间 2023-12-15 11:16:00作者: Gloria_Chen

处理文件时发现这个错误:

def Load_json():
json_file = 'C:\Python\assets\config.json'

with open(json_file, 'r') as fh:
data = json.load(fh)
print(data)
fh.close()

OSError: [Errno 22] Invalid argument: 'C:\\Python\x07ssets\\config.json'

后来发现是转义字符的问题。Python 解释器默认用 \ 作为转义字符,所以报错。

解决办法:

直接把单 \ 变成双 \\ : 

json_file = 'C:\Python\\assets\config.json'

 

Python 常用转义字符:
\ 反斜杠字符
‘ 单引号
“ 双引号
\a 响铃
\b 退格
\n 换行
\t 横向制表符
\r 回车
\f 换页