Import a file from a subdirectory?
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Underwater World
--
Chapters
00:00 Question
00:57 Accepted answer (Score 668)
01:18 Answer 2 (Score 214)
02:22 Answer 3 (Score 95)
02:36 Answer 4 (Score 49)
03:49 Thank you
--
Full question
https://stackoverflow.com/questions/1260...
Accepted answer links:
[Packages documentation (Section 6.4)]: https://docs.python.org/3/tutorial/modul...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pythonimport
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Underwater World
--
Chapters
00:00 Question
00:57 Accepted answer (Score 668)
01:18 Answer 2 (Score 214)
02:22 Answer 3 (Score 95)
02:36 Answer 4 (Score 49)
03:49 Thank you
--
Full question
https://stackoverflow.com/questions/1260...
Accepted answer links:
[Packages documentation (Section 6.4)]: https://docs.python.org/3/tutorial/modul...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pythonimport
#avk47
ACCEPTED ANSWER
Score 703
Take a look at the Packages documentation (Section 6.4).
In short, you need to put a blank file named
__init__.py
in the lib directory.
ANSWER 2
Score 228
- Create a subdirectory named
lib. - Create an empty file named
lib\__init__.py. In
lib\BoxTime.py, write a functionfoo()like this:def foo(): print "foo!"In your client code in the directory above
lib, write:from lib import BoxTime BoxTime.foo()Run your client code. You will get:
foo!
Much later -- in linux, it would look like this:
% cd ~/tmp
% mkdir lib
% touch lib/__init__.py
% cat > lib/BoxTime.py << EOF
heredoc> def foo():
heredoc> print "foo!"
heredoc> EOF
% tree lib
lib
├── BoxTime.py
└── __init__.py
0 directories, 2 files
% python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from lib import BoxTime
>>> BoxTime.foo()
foo!
ANSWER 3
Score 106
You can try inserting it in sys.path:
sys.path.insert(0, './lib')
import BoxTime
ANSWER 4
Score 31
Try import .lib.BoxTime. For more information read about relative import in PEP 328.