0

New to python and not understanding how imports work. I saw something about how you can do a sys.path.append but I don't want to do this because this needs to go into source control and run off multiple different computers with different pathing. How do I simply import a file that is in another folder but within the same project?

My file structure is

- Project

  - FolderA
    - FileA.py

  - FolderB
    - SubfolderB
      - FileB.py

How do I import FileA.py while inside FileB.py?

This doesn't work because I get back 'No Module named FolderA':

from FolderA import FileA

class FileB():
...  
Jeremy P
  • 1,309
  • 2
  • 13
  • 22
  • create a ` __init__.py ` file in each folder and then import function from there like `from foldera import func1` – sahasrara62 Feb 01 '19 at 22:37

2 Answers2

0

Add __init__.py to each directory to turn them into packages. Then you can use relative imports, such as in fileb.py

from ..FolderA import FileA

See Relative imports for the billionth time for detailed explanation of relative imports and how they work in python.

fstop_22
  • 971
  • 5
  • 9
0

Make your subfolders python packages

Make sure that only the root is on the python path.

Even better use a standard layout and use pip -e installs

See this for a great layout.

Then use absolute imports like import package.subpackage.module or explicit relative ones like import .module

Mihai Andrei
  • 1,024
  • 8
  • 11