首页 › 参考手册 › 内置函数 › open()

Python open() 函数

描述

打开文件并返回文件对象。常用模式:r 读、w 写(覆盖)、a 追加、b 二进制。处理文本时应始终指定 encoding。

语法

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

参数

参数说明
file文件路径
mode打开模式
encoding文本编码,推荐 utf-8

返回值

文件对象

实例

import tempfile, os
path = os.path.join(tempfile.gettempdir(), "demo_open.txt")
with open(path, "w", encoding="utf-8") as f:
    f.write("第一行\n第二行\n")
with open(path, encoding="utf-8") as f:
    print(f.readlines())
os.remove(path)
以上实例输出结果为:
['第一行\n', '第二行\n']