假设这是我的文件夹结构,
project
main_folder
file.py
json_files_folder
one.json
two.json
three.json
当我运行file.py
文件时,它应该获取json_files_folder
中文件的路径并打开一个文件,这是我的代码,
import json
import os
try:
file_path = os.path.dirname(os.path.realpath(__file__))
filename = file_path + '/' + 'one' + '.json'
with open(filename) as file:
data = json.load(file)
return data
except:
return "error"
我应该改变file_path变量使这段代码工作吗?提前感谢!
您的json
文件存在于json_files_folder
中,因此您需要遍历该路径以获取json
文件。下面是相同的代码:
import json
import os
try:
file_path = os.path.dirname(os.path.realpath(__file__))
filename = file_path + '/../json_files_folder/one.json'
with open(filename) as file:
data = json.load(file)
print (data)
except Exception as ex:
raise ex
另一个解决方案是使用Pathlib.Path
。
import json
from pathlib import Path
try:
base = Path(__file__).parent.parent
filename = base / 'json_files_folder' / 'one.json'
with open(filename) as file:
data = json.load(file)
print(data)
except:
return "error"