简体   繁体   中英

Python 3: How to import from different folder/directories

I've been working a lot lately with python 3 and I found that I am unable to import a module from a separate folder. Is there a way to import it while it's in a folder subdivision? To give more context of this issue here is the “launcher” location and folder that I want to access:

Launcher.py
Folder
- program-to-import.py

That's the layout. How do I import into launcher from my other module?

Python supports importing from child paths rather trivially. in Launcher.py enter the following.

from Folder.program-to-import import *

As mentioned by others, - in name is invalid, try importing after removing them if you have them in your file name. For now, let's call it program_to_import

from folder import program_to_import

And to call a function from program_to_import , you use this -

program_to_import.function_to_call()

Also, it's always a good idea to look at the documentation

You could also try by adding an __init__.py in your folder. The use of __init.py__ is as follows -

The init .py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later (deeper) on the module search path. In the simplest case, init .py can just be an empty file, but it can also execute initialization code for the package or set the all variable, described later.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM