代码点读机 / Python / open

open Python · 内置函数

打开一个文件,返回文件对象,用来读或写。

怎么用

open('文件名', 'r'/'w', encoding='utf-8')

小例子

with open('a.txt', 'w', encoding='utf-8') as f:
    f.write('hello')
with open('a.txt', 'r', encoding='utf-8') as f:
    print(f.read())

运行结果

hello

提醒:推荐配合 with 使用,自动关闭文件。

官方文档:https://docs.python.org/zh-cn/3/library/functions.html#open

在代码里遇到不认识的词?打开代码点读机,点一下就懂 → ← Python全部词条