Python 内置函数

Python open() 函数用于打开文件,返回文件对象,用于读写。

语法

open(file, mode='r', encoding=None)

参数

参数说明
file文件路径或文件对象
mode打开模式:r 读、w 写、a 追加、b 二进制
encoding可选,字符编码(写中文用 utf-8)
errors可选,编码错误处理方式

返回值

返回文件对象。支持 with 语句自动关闭;文件不存在或权限不足抛 OSError

示例

# 写文件
with open("demo.txt", "w", encoding="utf-8") as f:
    f.write("Hello\n")
    f.write("World\n")

# 读文件
with open("demo.txt", "r", encoding="utf-8") as f:
    content = f.read()
print(content)

# 逐行读
with open("demo.txt", "r") as f:
    for line in f:
        print(line.strip())

输出:

Hello
World
Hello
World

注意事项

模式:r 读、w 写(覆盖)、a 追加、b 二进制。写中文指定 encoding="utf-8"。用 with 自动关闭文件。