Python目录文件出错
Python directory file go wrong
我在读取 python 中的文件时遇到了一个愚蠢的问题。
我有一个文件夹 '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
而控制台returns出现这个错误:
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())
但它仍然returns给我这个错误:
FileNotFoundError: No such file or directory: 'D:\test.json'
任何人都可以帮助我获得正确的目录文件吗?
问题是您应该将 test.json
文件放在当前工作目录中。
即)例如,python 文件位于 C:\users\Desktop\Code\test.py
那么您应该将文件复制到 C:\users\Desktop\Code\
(或)
你应该在with open($PATH TO JSON FILE) as config_buffer
中给出文件的路径
如果您想从任何文件夹调用您的 python 脚本并让它在不指定路径的情况下访问其本地文件,您可以更改开头的目录:
import os
os.chdir(os.path.dirname(os.path.realpath(__file__)))
config_path = 'test.json'
...
我在读取 python 中的文件时遇到了一个愚蠢的问题。
我有一个文件夹 '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
而控制台returns出现这个错误:
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())
但它仍然returns给我这个错误:
FileNotFoundError: No such file or directory: 'D:\test.json'
任何人都可以帮助我获得正确的目录文件吗?
问题是您应该将 test.json
文件放在当前工作目录中。
即)例如,python 文件位于 C:\users\Desktop\Code\test.py
那么您应该将文件复制到 C:\users\Desktop\Code\
(或)
你应该在with open($PATH TO JSON FILE) as config_buffer
如果您想从任何文件夹调用您的 python 脚本并让它在不指定路径的情况下访问其本地文件,您可以更改开头的目录:
import os
os.chdir(os.path.dirname(os.path.realpath(__file__)))
config_path = 'test.json'
...