Home > Net >  with open FileNotFoundError: [Errno 2] No such file or directory:
with open FileNotFoundError: [Errno 2] No such file or directory:

Time:07-22

Here is the folder structure of my code:

project/
    latplan/
         __init__.py
         model.py
    samples/
         text.txt
    main2.py
lyrics/
    main.py

Content of each file:

main.py

#!/usr/bin/env python
import sys
sys.path.append(r"../project")
import latplan

... = some other code where latplan module was needed, then:

latplan.model.NN().load()

main2.py

#!/usr/bin/env python
import latplan

latplan.model.NN().load()

model.py

class NN():
    x = 5
    def load(self):
        with open("samples/text.txt", "r") as f:
            print("success")

When I execute main2.py (from project/ folder):

./main2.py

I get :

success

But when I execute main.py (from lyrics/ folder):

./main.py

I get the error:

"\lyrics../project\latplan\model.py", line 6, in load with open("samples/text.txt", "r") as f: FileNotFoundError: [Errno 2] No such file or directory: 'samples/text.txt

I can only modify main.py file, so how can I do so, in order to avoid this error ?

Thanks a lot

CodePudding user response:

If you can only modify main.py, the only workable approach is to change the working directory on launch. After modifying sys.path, you can add :

os.chdir('../project')

which will change your working directory for when it looks up new relative path names outside of import contexts (it will also affect import contexts, but only when the empty string is in sys.path, which by default only happens when run interactively, or when the script is read from stdin, neither of which are the expected case here).

  • Related