首页 > 解决方案 > Python读取路径错误

问题描述

所以我有这段代码可以打开一个 JSON 文件。(已导入 JSON)

with open("Python\videoid.json", "r") as json_file:

问题是 python 正在读取\v错误的部分并告诉我该文件不存在。有谁知道如何解决这个问题?

标签: pythonpath

解决方案


在 python '\' 是转义键中,python 是否认为您正在尝试使用转义字符,您可以通过制作原始字符串来解决此问题:

with open(r”Python\videoid.json", "r") as json_file:
# the r tells python to make it a raw string

或者您可以添加另一个反斜杠:

with open("Python\\videoid.json", "r") as json_file:
# tells python you want to actually do a backslash key

行上的注释解释了它。


推荐阅读