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

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.

11 Likes

how can we import more than one function form the same file?

library.py

function1():
function2():
...
....
functionn();

how to import all these functions together in another file script.py?

3 Likes

script.py:

import library   # note that we omit the  .py suffix

x = library.function1()      # called using "dot notation"
y = library.function2()
# etc

If you don’t want to type “library” each time:

import library as lib   # note that we omit the  .py suffix

x = lib.function1()      # called using "dot notation"
y = lib.function2()
# etc
11 Likes

What would be the correct way to import a file from a different directory, but not in a subfolder of the current file?
My boss is new to python and wants all the custom code in a different directory branch from the one that new scripts are developed and ‘launched’ from, for example (borrowing from your example):

“”"
development
–> project
----> myfile.py
custom
–> functions
----> file.py
----> __ init __.py
“”"

this is how the business code development is done using php so just ‘not doing it that way’ is not an option I have.

what do I do?

2 Likes

This appears to be very clear and complete.

5 Likes

you can do from library import* but use this * very carefully else not only it will pollute your namespaces but may conflict with local objects, functions.