The Python Oracle

Import a file from a subdirectory?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: A Thousand Exotic Places Looping v001

--

Chapters
00:00 Import A File From A Subdirectory?
00:43 Accepted Answer Score 700
01:02 Answer 2 Score 225
01:44 Answer 3 Score 106
01:56 Answer 4 Score 55
02:53 Answer 5 Score 30
03:04 Thank you

--

Full question
https://stackoverflow.com/questions/1260...

--

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 function foo() 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.