Python中打开文件主要用open()函数,推荐配合with语句和encoding参数使用,如with open("data.txt", "r", encoding="utf-8") as f: content = f.read()。

在 Python 中打开文件,主要用内置的 open() 函数。它返回一个文件对象,后续才能读写内容。
基本用法:open(文件路径, 模式)
最常用的形式是传入文件路径和打开模式(字符串):
- "r":只读(默认),文件必须存在,否则报错
- "w":写入,会清空原文件内容;若文件不存在则新建
- "a":追加,在文件末尾添加内容,不覆盖原有内容
- "r+":可读可写,文件必须存在
- 加上 "b"(如 "rb")表示二进制模式,处理图片、音频等非文本文件
推荐写法:配合 with 语句自动关闭
手动调用 .close() 容易遗漏,导致资源占用或写入失败。用 with 最安全:
```pythonwith open("data.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
```
离开 with 块后,文件自动关闭,无需写 f.close()。
标签: python windows 编码 win vs code
版权声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。
还木有评论哦,快来抢沙发吧~