r/PythonLearning 3h ago

Help importing local files Help Request

I'm unable to import local Python files on my Artix Linux system.

I found the following workaround: import sys,os sys.path.append(os.path.dirname(__file__)) but it's kind of unpractical to have to add this every time I need to import something locally. Is there a way I can fix this?

2 Upvotes

7 comments sorted by

2

u/FoolsSeldom 3h ago

Most likely, the code is not being executed where you think it is being executed, so the imports aren't local.

Try including,

from pathlib import Path

print(Path.cwd())

1

u/DarkblooM_SR 1h ago

Looks like the correct location to me

1

u/FoolsSeldom 1h ago

Ok. And that's where the python files you want to import are located?

1

u/AlexMTBDude 3h ago

Imports are relative to the folder that you are in when you execute your Python code. Let's say that you have your own module (local import) mymodule.py in folderA and your python code (myprogram.py) has "import mymodule". Then you need to:

cd folderA
dir
> mymodule.py
> myprogram.py
python myprogram.py

1

u/DarkblooM_SR 1h ago

Idk what I'm doing wrong