我在python中读取文件时遇到了愚蠢的问题。
我的Have文件夹是'a',其中包含我的test.py和要读取的文件test.json
我的test.py看起来像这样:
config_path = 'test.json'
with open(config_path) as config_buffer:
config = json.loads(config_buffer.read())
我站在文件夹'a'外面,然后运行命令:
python a\test.py
并且控制台对我返回错误:
FileNotFoundError: No such file or directory: 'test.json'
我尝试使用pathlib使用绝对文件路径:
config_path = Path('end2end.json').absolute()
with open(config_path) as config_buffer:
config = json.loads(config_buffer.read())
但是它仍然向我返回错误:
FileNotFoundError: No such file or directory: 'D:\\test.json'
任何人都可以帮助我获取确切的目录文件吗?
test.json
文件放置在当前工作目录中。i.e)例如,python文件位于C:\users\Desktop\Code\test.py
中,则应将文件复制到C:\users\Desktop\Code\
(或)
您应该在with open($PATH TO JSON FILE) as config_buffer
中提供文件的路径
import os
os.chdir(os.path.dirname(os.path.realpath(__file__)))
config_path = 'test.json'
...