1

I need to import a function x of file X from directory A to file Y of directory B but the the file X also imports function z of file Z from A directory itself. Directory A is inside directory C and directories B and C are at same level. I tried adding A to sys path and doing 'from X import x' but it threw no module found error and also I added C to path and did from A.X import x but same error.Y is able to import x from X but when X executes and reads import for Z it throws error.

Dir structure :

├───C
│   ├───A
│   │   ├───X
│   │   ├───Z
└───B
    └───Y
  • When posting questions, always add what have you tried that did not work? Additionally, writing your directory in a directory tree structure can help reviewers answer your question. – Merelda Nov 27 '19 at 07:10
  • With complex file structures, having multiple sys.path can be cumbersome and make the import part of the module very messy. [Try use `pip install -e .` instead](https://stackoverflow.com/questions/714063/importing-modules-from-parent-folder/50194143#50194143) – Merelda Nov 27 '19 at 08:12

1 Answers1

0

I scribbled the directory structure you said to understand the question I cannot post it due to low reputation.

Python resolves file import paths from the place you are executing the file now

There are two three ways you can actually import the file z

One way is you use os.chdir() to change directory before you import something so that you resolve paths, but wouldn't recommend this

Other way is you add the z to your sys.path this way you don't have to resolve path but the python interpreter will look into the A folder whenever you write import x from X or Z from z

But make sure the path you add in the sys.path is from the current directory or it is a full path.

You can also add the A Folder to PYTHONPATH