Home >Backend Development >Python Tutorial >Python Tutorial: Learn how to read .py files

Python Tutorial: Learn how to read .py files

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2024-04-04 11:21:01780browse

可以通过以下两种方式读取 .py 文件并导入自定义模块:使用 importlibimportlib 模块提供了 import_module() 函数,可动态导入文件,并返回指向导入模块的引用。 使用 open()open() 函数可打开文件并返回指向文件对象的引用,文件对象具有 read() 方法,可读取文件内容。

Python Tutorial: Learn how to read .py files

Python 教程:读取 .py 文件

导入必要的模块

import os
import importlib

使用 importlib

importlib 模块提供了一个 import_module() 函数,可动态导入文件。此方法返回指向导入模块的引用。

file_path = "my_module.py"
my_module = importlib.import_module(file_path)

使用 open()

open() 函数可打开文件并返回指向文件对象的引用。文件对象具有 read() 方法,可读取文件内容。

with open(file_path, "r") as f:
    file_contents = f.read()

实战案例:读取自定义模块

假设有一个名为 my_module.py 的自定义模块:

# my_module.py
def greet(name):
    print(f"Hello, {name}!")

现在,让我们从另一个脚本中读取此模块:

# main.py
import os
import importlib

file_path = "my_module.py"
my_module = importlib.import_module(file_path)

my_module.greet("John")

输出:

Hello, John!

The above is the detailed content of Python Tutorial: Learn how to read .py files. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn