Search code examples
pythonjsonjupyter-laberrno

FileNotFoundError: [Errno 2] JSON file


Background -
I'm trying to read a JSON file into Jupyter Lab, that I subsequently want to write to a csv file.

Issue -
My code should be going up a dir level, going into a 'Resources' folder and reading the 'restaurant.json', however when I run my code, Jupyter Lab keeps throwing an issue -

Error -
FileNotFoundError: [Errno 2] No such file or directory: '../Resources/restaurant.json'

Code -

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

Folder Structure -
My Jupyter Lab file - /Users/MyUserName/Documents/davis/Homework_Repos/ETL-project/working/will.ipynb
My JSON file - /Users/MyUserName/Documents/davis/Homework_Repos/ETL-project/Resources/restaurant.json

What I think -
I have another project with an identical setup in terms of code, with the only difference being the JSON file name and it read the file perfectly. My only suspicion is that the restaurant.json file is 10MB in size, so I wonder if this is causing issues

Any advice would be much appreciated - perhaps my code needs to be more implicit!


Solution

  • Use pathlib

    • This module offers classes representing filesystem paths with semantics appropriate for different operating systems.
    • It's part of the standard library and should replace os.
    • Python 3's pathlib Module: Taming the File System
    • With cwd as WindowsPath('Users/MyUserName/Documents/davis/Homework_Repos/ETL-project/working')
      • cwd.parents[0] is WindowsPath('Users/MyUserName/Documents/davis/Homework_Repos/ETL-project')
      • cwd.parents[1] is 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())