python引入其他資料夾裡的py檔案的方法

2021-10-09 16:44:18 字數 1786 閱讀 1781

在寫python框架的時候,經常會用到引入其他資料夾裡的python檔案,要是都在同目錄下的還好,直接import就好了,可是有的不在同乙個目錄,很多初學者就發現直接import報錯了

如下圖,test_a.py和test_b.py檔案都在同乙個目錄

要在test_b裡引入test_a的話,直接在test_b裡import

反之亦

如果工程目錄是這樣的,想要在test_d裡引入test_c.py檔案

test_c.py裡有個方法c,如圖

方法1:直接import

#引入test_c.py檔案

import testfile.test_c

print('這是test_d')

方法2:from…import…

#引入test_c.py檔案

from testfile.test_c import c

print('這是test_d')

c()

有一種可能在引入的時候會報錯,這時候有乙個很簡單的方法,就是在資料夾裡多建乙個__init__.py檔案

2.1 在資料夾裡加個__init__.py檔案

在testfile資料夾裡加上__init__.py檔案,注意是兩個_

這時候再執行test_d.py檔案,沒報錯了

當路徑是這樣的

test_1.py檔案裡有test1的方法

要在test_2.py檔案裡引入test_1.py

import sys

from dir_1.test_1 import test1

test1()

綜上所述,其實引入其他檔案的方法有兩種,乙個是直接import,乙個是from…import…

其實引入python庫的方法也是這樣的

有時候庫名很長,可以用as 別名的方法來

比如引入selenium庫里的鍵盤庫,取個ac的別名,下面就直接用ac來代替actionchains了

from selenium.webdriver.common.action_chains import actionchains as ac

python引入其他資料夾下的py檔案具體方法

紅色方框要引入箭頭裡面的 import sys symtuxbms.path.append config from database import print mysql config 內容擴充套件 python的import包含檔案功能就跟php的include類似,但更確切的說應該更像是php中...

Python 複製A資料夾裡的檔案到B資料夾

問題描述 a資料夾裡都是xml檔案,b檔案是乙個空資料夾,c資料夾裡面都是jpg檔案,現在要在 資料夾中挑選出含有b資料夾裡jpg檔案名字的xml檔案儲存到b中。例如 中含有888.jpg檔案,要在 中挑選出888.xml儲存到b coding utf 8 import os,shutil dir1...

python檔案重新命名(括子資料夾裡的檔案

python檔案重新命名 括子資料夾裡的檔案 coding utf 8 time 2020 5 27 13 15 author 王巖 import os def path file path file path為資料夾路徑 for root,dirs,files in os.walk file pa...