skip to Main Content
parentDirectory
    subdr1
        -testfile.txt
    subdr2
        childdir
           -file.json
           -file2.pickle
        -fileOpener.py 

I would like to read the file.json from fileOpener.py in Python using:

with open("./childdir/file.json", 'r') as f:

But I’m getting FileNotFoundError.

FileNotFoundError: [Errno 2] No such file or directory: './childdir/file.json'

Would anyone mind solving this issue? I’m using WINDOWS operating system.

3

Answers


  1. First of all which OS are you using ? since windows uses and UNIX based OSes use /

    Bast approach would be to use path from os module like this:

    import os
    
    with open(os.path.join('childdir', 'file.json'), 'r')" as f:
        # YOUR CODE
    

    This is a better approach because it is platform independent since it creates the path appropriately based on the OS you are on.

    Login or Signup to reply.
  2. This is because the file you want to open is in the subdirectory of your current working directory(where the python file is present).
    You need to consider 2 things here,

    1. Depends on the OS which you’re using, it’s either ‘/’ for UNIX-based &
      ” for Windows-based as separator in the file’s path

    2. we can either use the absolute path of the file and mode to open the file
      or with the path sub-module of that os module.

    # With absolute path in Windows 
     with open('F:parentDirectorysubdr2childdirfile.json', mode(r/a/w..)) as fl:
             # logic
    

    or

    # with os.path submodule
      import os
    
      with open(os.path.join('childdir', 'file.json'), mode('r/w/a/..')) as fl:
            # logic
    
    
    Login or Signup to reply.
  3. If you run fileOpener.py within the subdir2 then all is well. The problem happens when you are not in subdir2. Here is the solution:

    import pathlib
    
    this_script = pathlib.Path(__file__)
    json_path = this_script.parent / "childdir" / "file.json"
    with open(json_path, 'r') as f:
        ...
    

    Since pathlib is cross-platform, this code should work under Windows. I tested it under Mac and linux.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search