如何打开与Python脚本位于同一文件夹中的文件

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

我有一个名为study的文件夹,其中有一个名为data.json的JSON文件,但是当我尝试使用同一文件夹中的python脚本打开它时,我得到了FileNotFoundError: [Errno 2] No such file or directory: 'data.json'

但是,当我使用完整的绝对路径到data.json时,它起作用。

如何解决此问题,以便可以将data.json的路径指定为与.py文件位于同一文件夹中?

这是我的代码:

import json

data = json.load(open("data.json"))

def translate(w):
    return data[w]

word = input("Enter word: ")

print(translate(word))

python json python-3.x datasource
2个回答
1
投票

使用__file__。这将使您能够指定相对于Python脚本文件位置的路径。

__file__

或者,使用import os data_file_path = os.path.join(os.path.dirname(__file__), "data.json") data = json.load(open(data_file_path)) 代替pathlib

os

0
投票
from pathlib import Path

data_file_path = Path(__file__).parent / "data.json"
data = json.load(open(data_file_path))

检查哪个是您当前的工作目录。如果需要,请更改。

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