要在Python中導(dǎo)入本地文件,可以使用importlib
模塊的import_module
函數(shù)或exec
函數(shù)來實(shí)現(xiàn)。以下是兩種方法的示例:
importlib
模塊的import_module
函數(shù):import importlib.util
# 指定本地文件的路徑
file_path = "path/to/your/file.py"
# 使用import_module函數(shù)導(dǎo)入本地文件
spec = importlib.util.spec_from_file_location("module_name", file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
exec
函數(shù):# 指定本地文件的路徑
file_path = "path/to/your/file.py"
# 使用exec函數(shù)執(zhí)行本地文件
with open(file_path, "r") as file:
code = file.read()
exec(code)
請注意,使用exec
函數(shù)導(dǎo)入本地文件可能會(huì)存在一些安全風(fēng)險(xiǎn),因?yàn)樗试S執(zhí)行任意代碼。因此建議在導(dǎo)入未知來源的文件時(shí)要格外小心。