Method: Change curent path to parent dir (target dir) Tips: If you run the code in terminal, swith the path to sub_dir2 (The dir of your sub_test.py in).
Method: The same as part 4. Change curent path to parent dir. Tips: If you run the code in terminal, swith the path to sub_dir2 (The dir of your sub_test.py in).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#parent_test.py import sys sys.path.append("..")
## Method 1 from sub_dir1 import sub_file sub_file.sub_fun()
## Method 2 from sub_dir.sub_file import sub_fun sub_fun()
## Method 3 import sub_dir.sub_file as sub_file sub_file.sub_fun()
6 Supplementary
6.1 __init__.py
Usually, we need to create a blank __init__.py file in our dir of .py file to be imported. However, in my experiments (python 3.9.7 as interpreter), all above 4 types work well without __init__.py.
6.2 How import works?
Please see the following experiment results.
6.3 Path
sys.path.append() is used to add new path to the default path.
1 2 3 4 5 6 7 8 9 10 11
(LiziX) D:\research\programming\python\python_import\parent_dir\sub_dir2>python Python 3.9.7 (default, Sep 16 2021, 16:59:28) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> print(sys.path) ['', 'D:\\software\\anaconda\\next\\envs\\LiziX\\python39.zip', 'D:\\software\\anaconda\\next\\envs\\LiziX\\DLLs', 'D:\\software\\anaconda\\next\\envs\\LiziX\\lib', 'D:\\software\\anaconda\\next\\envs\\LiziX', 'D:\\software\\anaconda\\next\\envs\\LiziX\\lib\\site-packages', 'D:\\software\\anaconda\\next\\envs\\LiziX\\lib\\site-packages\\win32', 'D:\\software\\anaconda\\next\\envs\\LiziX\\lib\\site-packages\\win32\\lib', 'D:\\software\\anaconda\\next\\envs\\LiziX\\lib\\site-packages\\Pythonwin'] >>> sys.path.append("D:\\software\\anaconda\\next\\envs\\LiziX\\python39.zip") >>> print(sys.path) ['', 'D:\\software\\anaconda\\next\\envs\\LiziX\\python39.zip', 'D:\\software\\anaconda\\next\\envs\\LiziX\\DLLs', 'D:\\software\\anaconda\\next\\envs\\LiziX\\lib', 'D:\\software\\anaconda\\next\\envs\\LiziX', 'D:\\software\\anaconda\\next\\envs\\LiziX\\lib\\site-packages', 'D:\\software\\anaconda\\next\\envs\\LiziX\\lib\\site-packages\\win32', 'D:\\software\\anaconda\\next\\envs\\LiziX\\lib\\site-packages\\win32\\lib', 'D:\\software\\anaconda\\next\\envs\\LiziX\\lib\\site-packages\\Pythonwin', 'D:\\software\\anaconda\\next\\envs\\LiziX\\python39.zip'] >>> ^Z
-------------End of blogThanks for your reading-------------