Python 读取 txt 文件详解 with ... open()
文章目录
- 1 概述
- 1.1 注意事项
- 1.2 模式说明
- 1.3 文件准备
- 2 读文件
- 2.1 读取整个文件
- 2.2 逐行读取
- 2.3 读取所有行到列表
- 3 写文件
- 3.1 覆盖写入
- 3.2 追加写入
- 3.3 写入多行
- 4 实用技巧
- 4.1 检查文件是否存在
- 4.2 异常处理
1 概述
1.1 注意事项
- 文件编码:建议指定编码(如:
utf-8
),避免在不同平台上出现编码问题。 - with 语句:可以自动处理文件的打开和关闭,避免资源泄露。
1.2 模式说明
模式 | 描述 |
---|---|
r | 只读(默认) |
w | 写入(会覆盖已有文件) |
x | 独占创建(若文件已存在,则失败) |
a | 追加(若文件不存在,则创建) |
b | 二进制模式 |
t | 文本模式(默认) |
+ | 更新(可读写) |
例如:
r+
:可读写;wb
:二进制写入
1.3 文件准备
- 在桌面创建文件
file.txt
,并复制以下内容
这是文件的第 1 行
这是文件的第 2 行
这是文件的第 3 行
2 读文件
2.1 读取整个文件
file = r'C:\Users\Administrator\Desktop\file.txt'with open(file, 'r', encoding='utf-8') as f:content = f.read() # 读取全部内容为一个字符串print(content)
2.2 逐行读取
file = r'C:\Users\Administrator\Desktop\file.txt'with open(file, 'r', encoding='utf-8') as f:for line in f: # 逐行迭代,内存高效print(line.strip()) # strip()去掉首尾空白和换行符
2.3 读取所有行到列表
file = r'C:\Users\Administrator\Desktop\file.txt'with open(file, 'r', encoding='utf-8') as f:lines = f.readlines() # 返回包含所有行的列表print(lines)
3 写文件
3.1 覆盖写入
file = r'C:\Users\Administrator\Desktop\file.txt'with open(file, 'w', encoding='utf-8') as f:f.write('第一行内容\n')f.write('第二行内容\n')
3.2 追加写入
file = r'C:\Users\Administrator\Desktop\file.txt'with open(file, 'a', encoding='utf-8') as f:f.write('追加的内容\n')
3.3 写入多行
file = r'C:\Users\Administrator\Desktop\file.txt'lines = ['第一行\n', '第二行\n', '第三行\n']
with open(file, 'w', encoding='utf-8') as f:f.writelines(lines) # 写入字符串列表
4 实用技巧
4.1 检查文件是否存在
import osfile = r'C:\Users\Administrator\Desktop\file.txt'if os.path.exists(file):print('存在') # 文件存在时的操作
else:print('不存在')
4.2 异常处理
file = r'C:\Users\Administrator\Desktop\file.txt'try:with open(file, 'r', encoding='utf-8') as f:content = f.read()print(content)
except FileNotFoundError:print("文件不存在")
except UnicodeDecodeError:print("编码错误")