FileNotFoundError: [Errno 2] JSON file

FileNotFoundError: [Errno 2] JSON file

背景 -
我正在尝试将 JSON 文件读入 Jupyter Lab,随后我想将其写入 csv 文件。

问题-
我的代码应该上升到目录级别,进入 'Resources' 文件夹并读取 'restaurant.json',但是当我 运行 我的代码时,Jupyter Lab 不断抛出问题 -

错误-
FileNotFoundError: [Errno 2] 没有这样的文件或目录: '../Resources/restaurant.json'

代码-

import json
import csv
import os
filepath = os.path.join("..", "Resources", "restaurant.json")
with open(filepath) as jsonfile:
    json_data = json.load(jsonfile)

文件夹结构-
我的Jupyter Lab文件-/Users/MyUserName/Documents/davis/Homework_Repos/ETL-project/working/will.ipynb
我的JSON文件-/Users/MyUserName/Documents/davis/Homework_Repos/ETL-project/Resources/restaurant.json

我的想法 -
我有另一个项目在代码方面具有相同的设置,唯一的区别是 JSON 文件名它完美地读取了文件。我唯一的怀疑是 restaurant.json 文件大小为 10MB,所以我想知道这是否会导致问题

任何建议都会很多感谢 - 也许我的代码需要更隐含!

使用pathlib

  • 此模块提供 类 表示文件系统路径的语义适用于不同的操作系统。
  • 它是标准库的一部分,应该取代 os
  • Python 3's pathlib Module: Taming the File System
  • cwd一样WindowsPath('Users/MyUserName/Documents/davis/Homework_Repos/ETL-project/working')
    • cwd.parents[0]WindowsPath('Users/MyUserName/Documents/davis/Homework_Repos/ETL-project')
    • cwd.parents[1]WindowsPath('Users/MyUserName/Documents/davis/Homework_Repos')
from pathlib import Path
import json

cwd = Path.cwd()
file = cwd.parents[0] / 'Resources' / 'restaurant.json'

with file.open('r', encoding='utf-8') as f:
    data = json.load(f.read())