温馨提示×

python中如何导入本地文件

小亿
287
2024-03-18 10:34:58
栏目: 编程语言
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

要在Python中导入本地文件,可以使用importlib模块的import_module函数或exec函数来实现。以下是两种方法的示例:

  1. 使用importlib模块的import_module函数:
import importlib.util

# 指定本地文件的路径
file_path = "path/to/your/file.py"

# 使用import_module函数导入本地文件
spec = importlib.util.spec_from_file_location("module_name", file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
  1. 使用exec函数:
# 指定本地文件的路径
file_path = "path/to/your/file.py"

# 使用exec函数执行本地文件
with open(file_path, "r") as file:
    code = file.read()
    exec(code)

请注意,使用exec函数导入本地文件可能会存在一些安全风险,因为它允许执行任意代码。因此建议在导入未知来源的文件时要格外小心。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:pycharm如何导入本地文件

0