读写文件
文件操作是 Python 编程中的重要功能之一。通过文件读写操作,程序可以与本地文件系统交互,实现数据的持久化存储和处理。
1. 文件的打开与关闭
在 Python 中,操作文件的第一步是用 open()
函数打开文件。文件打开后一定要关闭,否则可能会占用系统资源或引发数据不完整的问题。
1) open()
函数
open(file, mode, encoding)
是打开文件的主要方法。
参数 | 描述 |
---|---|
file |
文件路径,可以是相对路径或绝对路径。 |
mode |
文件操作模式(读、写、追加等)。 |
encoding |
文件编码(通常是 utf-8 )。 |
2) 常见模式
模式 | 描述 |
---|---|
r |
以只读模式打开文件(默认)。 |
w |
以写入模式打开文件,清空原内容。 |
a |
以追加模式打开文件,写入到末尾。 |
b |
二进制模式(可与其他模式组合)。 |
3) 示例
# 打开文件(读模式)
file = open("example.txt", "r", encoding="utf-8")
# 关闭文件
file.close()
为了避免忘记关闭文件,推荐使用 with
语句。
2. 读取文件
Python 提供多种方法读取文件内容,根据需求选择合适的方式。
1) 按行读取:readline()
一次读取文件的一行内容。
with open("example.txt", "r", encoding="utf-8") as file:
line = file.readline()
while line:
print(line.strip()) # 使用 strip() 去除换行符
line = file.readline()
2) 全部读取:read()
将整个文件内容作为一个字符串返回。
with open("example.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)
3) 按行读取到列表:readlines()
将文件中的每一行作为一个列表元素。
with open("example.txt", "r", encoding="utf-8") as file:
lines = file.readlines()
for line in lines:
print(line.strip())
3. 写入文件
使用写入模式或追加模式向文件写入内容。
1) 写入字符串:write()
with open("example.txt", "w", encoding="utf-8") as file:
file.write("Hello, Python!\n")
file.write("学习文件操作吧!")
2) 写入多行:writelines()
接受一个字符串列表并逐行写入文件。
lines = ["第一行\n", "第二行\n", "第三行\n"]
with open("example.txt", "w", encoding="utf-8") as file:
file.writelines(lines)
4. 追加内容
追加模式 a
不会清空原文件,而是将新内容追加到文件末尾。
with open("example.txt", "a", encoding="utf-8") as file:
file.write("\n追加内容:欢迎学习 Python 文件操作!")
5. 文件操作示例:读写结合
实现一个简单的文件操作任务:将一个文件的内容读取并写入到另一个文件中。
# 从 source.txt 读取内容,并写入到 target.txt
with open("source.txt", "r", encoding="utf-8") as source:
content = source.read()
with open("target.txt", "w", encoding="utf-8") as target:
target.write(content)
6. 处理异常
文件操作中可能会遇到文件不存在或读取失败等问题。可以通过 try...except
处理异常。
try:
with open("non_existent.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("文件不存在,请检查文件路径!")
7. 文件路径问题
1) 相对路径
文件路径基于当前脚本位置。例如:
with open("data/example.txt", "r", encoding="utf-8") as file:
print(file.read())
2) 绝对路径
完整路径,适合跨目录操作。例如:
with open("C:/Users/username/data/example.txt", "r", encoding="utf-8") as file:
print(file.read())
3) 使用 os
模块
用 os.path
处理路径更灵活:
import os
file_path = os.path.join("data", "example.txt")
with open(file_path, "r", encoding="utf-8") as file:
print(file.read())
8. 文件读写注意事项
- 资源释放:推荐使用
with
语句,避免手动调用close()
。 - 文件模式匹配:根据需求选择
r
、w
或a
模式。 - 避免覆盖:写模式会清空文件,操作前需谨慎。
- 编码问题:文本文件通常使用
utf-8
,避免乱码。
9. 总结
- 文件读写是 Python 中的基础操作,通过
open()
函数和文件对象的方法,可以轻松实现对文本文件的操作。 - 通过灵活使用
read
、write
等方法,结合异常处理和路径操作,可以编写出健壮的文件处理程序。
示例练习:实现一个简单的记事本程序,用户可以通过输入保存内容到文件,并可以随时查看历史记录。