简体   繁体   中英

Errno 2 No such file or directory error while importing a python script from a sub-folder

I have a python script (db.py) which has a class(Chat) which refers to a json file(cred.json) saved in the same folder(db). This script runs perfectly fine without any error.

When I try to import the class Chat in a python script(wa.py) which is saved in one folder above folder db I get an error saying "[Errno 2] No such file or directory".

My folder structure looks like below

- wa.py
- db
    - db.py
    - cred.json

Piece of code in db.py where I am referring to the json file

cred_filename = 'creds.json'
with open(cred_filename, 'r') as c:
    data = json.load(c)

wa.py looks like this

from db.db import Chat

I tried to find answer on google but couldn't find a relevant explanation for my case. I know there is something fundamentally wrong here but I am not able to figure it out.

Thanks in advance.

Essentially you're trying to open creds.json which is relative to your current working directory (unless changed during the runtime, one you have been in when calling the script) which does not need to be and apparently when this happens is not the one in which db.py resides.

This can only work and worked, as long as you were already in db/ when importing / running db.py .

If you always wanted to get creds.json in the directory where db.py resides, you could say for instance:

from pathlib import Path
...
cred_filename = Path(__file__).with_name("creds.json")

That takes path of the file this module is imported from and replaces the filename part with "creds.json" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM