Python目录文件出错

问题描述 投票:0回答:2

我在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'

任何人都可以帮助我获取确切的目录文件吗?

python filepath readfile absolute-path
2个回答
0
投票
问题是您应该将test.json文件放置在当前工作目录中。

i.e)例如,python文件位于C:\users\Desktop\Code\test.py中,则应将文件复制到C:\users\Desktop\Code\

(或)

您应该在with open($PATH TO JSON FILE) as config_buffer中提供文件的路径


0
投票
如果要从任何文件夹调用python脚本,并让其访问本地文件而无需指定路径,则可以在开头更改目录:

import os os.chdir(os.path.dirname(os.path.realpath(__file__))) config_path = 'test.json' ...

© www.soinside.com 2019 - 2024. All rights reserved.