Shawn's blog Shawn's blog
About Me
  • Category
  • Tag
  • Archive
GitHub (opens new window)

Shawn Jin

I am not a creator of knowledge, I am just a porter of knowledge.
About Me
  • Category
  • Tag
  • Archive
GitHub (opens new window)
  • Python

    • Python import files from different directories
      • 0x01: When runner.py and test.py are under same directory
      • 0x10: When test.py is under runner.py's child's directory
      • 0x11: When test.py is under parent directory of runner.py
    • Single/Double Star (*/**) Parameters in Python
    • Classmethod in Python
    • Python modify range variable in for loop
  • Git

  • Notes
  • Python
Shawn Jin
2019-12-31

Python import files from different directories

# Python import files from different directories

Python is a object-oriented language like java, so we could use a file to represent an object or something else. When we want to import files in Python, there are 3 cases that we need to concern and know how to deal with it.

Supposed we have a runner program in file runner.py and an Add class file in file test.py

# 0x01: When runner.py and test.py are under same directory

you can import the class directly by file name. However, you need to ignore the .py suffix/postfix. like below:

# 1: import whole file
import test
# 2: import specific portion
from test import Add
1
2
3
4

then you are free to use it.

# 0x10: When test.py is under runner.py's child's directory

Supposed the directory name is test as well In this case you can import the class by import [directory]/[filename(without suffix)] and below is my example:

# 1: import whole file
import test.test as aa
# 2: import specific portion
from test.test import Add

1
2
3
4
5

# 0x11: When test.py is under parent directory of runner.py

In this case, you need to import sys and append/insert the current directory info to sys.path at run time.

# add system path at run-time
import sys
########### The path MUST be absolute path ###############
sys.path.append('absolute/path/to/your/file')
# 1: import specific method 
from my_print import test_my_print as print
# 2: import whole file
import my_print
1
2
3
4
5
6
7
8

In fact, you can handle every import cases in this way, but we don't have to change the sys.path for case 0x01 and 0x10.

The runnable source code (opens new window) could help your figure it out better.

#Python
Updated: 2021/09/05, 15:42:35
Single/Double Star (*/**) Parameters in Python

Single/Double Star (*/**) Parameters in Python→

最近更新
01
Classmethod in Python
09-15
02
Single/Double Star (/*) Parameters in Python
09-15
03
Backprop Algorithm in Machine Learning
09-08
更多文章>
Theme by Vdoing | Copyright © 2019-2021 Shawn Jin | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式