0

I busy with some calculations in Python and therefore i have some bunch of scripts. I have tried to clean this up thru 2 folders named scripts and tests. Now i have the problem that my main Python file don't recognize the scripts in the subfolders.
So my import filename don't work anny more. When i look in some git files it looks like the don mention paths and still it works.
I had looked at this SE question but that gave me a error (ImportError: No module named "filename")

What have i to do in my main script, subfolder or files in subfolders.

my scripts are no classes yet... Probably not all become classes. so a generic solution is best

Community
  • 1
  • 1
Jan-Bert
  • 921
  • 4
  • 13
  • 22

1 Answers1

0

You can do relative imports from where you are. Let's assume you're importing from the file /home/janbert/projects/test/test.py

If you want to import /home/janbert/projects/test/subdir/file.py you write:

from subdir import file

And if you want to import /home/janbert/projects/otherproject/subdir/file.py you write:

from ..otherproject.subdir import file

Just remember that each python package (ie folder) must have a file named __init__.py (which can be empty), otherwise you can not import from that package.

olofom
  • 6,233
  • 11
  • 37
  • 50
  • Is it in this way also possible to just run a file (no `def` in it)? in this case that `file.py` runs it own script and don't put it back in the first one(generate some data; do something and create some figures)? – Jan-Bert Feb 07 '16 at 20:17
  • @Jan-Bert if you have code straight up in the imported file and not in functions in it it should be executed on import, just create an empty file with a print and see what happens. It's not advisable though, you should create functions and execute them explicitly instead. – olofom Feb 07 '16 at 22:47