【问题标题】:FileNotFoundError: [Errno 2] JSON fileFileNotFoundError:[Errno 2] JSON 文件
【发布时间】:2020-07-03 00:15:14
【问题描述】:

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

问题 -
我的代码应该上升到 dir 级别,进入“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,所以我想知道这是否会导致问题

任何建议将不胜感激 - 也许我的代码需要更多隐含的!

【问题讨论】:

    标签: python json jupyter-lab errno


    【解决方案1】:

    使用pathlib

    • 该模块提供了代表文件系统路径的类,其语义适用于不同的操作系统。
    • 它是标准库的一部分,应该替换 os
    • Python 3's pathlib Module: Taming the File System
    • cwdWindowsPath('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())
    

    【讨论】:

      猜你喜欢
      • 2020-09-15
      • 2014-11-13
      • 1970-01-01
      • 2020-10-18
      • 1970-01-01
      • 2019-08-06
      • 1970-01-01
      • 1970-01-01
      • 2019-09-20
      相关资源
      最近更新 更多