Home > Back-end >  Showing FileNotFound Error when trying to open file from another directory in python
Showing FileNotFound Error when trying to open file from another directory in python

Time:08-26

\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?

CodePudding user response:

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.

CodePudding user response:

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 path sub module of that os module.

    With absolute path in Windows

    with open('F:\parentDirectory\subdr2\childdir\file.json', mode(r/a/w..)) as fl: # logic

    with os.path submodule

    import os

    with open(os.path.join('childdir', 'file.json'), mode('r/w/a/..')) as fl: # YOUR CODE

  • Related