Do imported files always have to be in the same directory?


#1

Question

In the context of this exercise, do imported files always have to be in the same directory as the file we are importing to?

Answer

No, files can be imported from different directories.

There are a few ways you can do this, and one of them is importing a file from a subdirectory. For example, say that you have this folder structure,

"""
project
--> myfile.py
--> functions
----> file.py
----> __init__.py
"""

In the myfile.py file, we can import a function from the file.py file, like so

from functions.file import function1

One thing to note when importing a file from another directory in this way, is that you would need to include a file named __init__.py in the same directory of that file being imported. In the above example folder structure, we included __init__.py in the same directory as file.py. This lets Python know that a file is a package from which to import modules from.