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

Python Tutorial: Learn how to read .py files

WBOY
Release: 2024-04-04 11:21:01
Original
753 people have browsed it

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

Python Tutorial: Learn how to read .py files

Python 教程:读取 .py 文件

导入必要的模块

import os
import importlib
Copy after login

使用 importlib

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

file_path = "my_module.py"
my_module = importlib.import_module(file_path)
Copy after login

使用 open()

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

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

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

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

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

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

# main.py
import os
import importlib

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

my_module.greet("John")
Copy after login

输出:

Hello, John!
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template