Python文件读写方法教程
文件读取基础
文件读取是Python中最常见的操作之一,主要使用内置的`open()`函数实现。
1. 使用`open()`函数打开文件,语法为`open(filename, mode)`。
- 读取文件内容的主要方法:
- `read()`: 读取整个文件内容
- `readline()`: 读取一行内容
- `readlines()`: 读取所有行并返回列表
# 打开文件(需要提前创建example.txt)
file = open('example.txt', 'r')
# 读取整个文件
content = file.read()
print("完整内容:")
print(content)
# 重置文件指针到开头
file.seek(0)
# 逐行读取
print("\n逐行读取:")
line = file.readline()
while line:
print(line.strip()) # 去除换行符
line = file.readline()
# 关闭文件
file.close()
文件写入基础
文件写入同样使用`open()`函数,但需要指定写入模式。
# 覆盖写入
file = open('output.txt', 'w')
file.write("这是第一行\n")
file.write("这是第二行\n")
# 写入字符串列表
lines = ["第三行\n", "第四行\n"]
file.writelines(lines)
file.close()
# 追加写入
file = open('output.txt', 'a')
file.write("这是追加的内容\n")
file.close()
使用with语句(推荐)
使用`with`语句可以自动管理文件资源,避免忘记关闭文件。
# 读取文件示例
with open('example.txt', 'r') as file:
content = file.read()
print(content)
# 文件自动关闭
# 写入文件示例
with open('example.txt', 'w') as file:
file.write("使用with语句写入的内容\n")
# 文件自动关闭
二进制文件读写
对于非文本文件(如图片、视频),需要使用二进制模式。
- 二进制模式:
- 'rb': 二进制读取
- 'wb': 二进制写入
- 'ab': 二进制追加
# 复制图片文件(二进制读写)
with open('source.jpg', 'rb') as src_file:
binary_data = src_file.read()
with open('copy.jpg', 'wb') as dest_file:
dest_file.write(binary_data)
print("图片复制完成")
文件指针和定位
文件指针指示当前读写位置,可以通过方法进行控制。
- `tell()`: 获取当前指针位置
- `seek(offset, whence)`: 移动指针位置
- offset: 偏移量
- whence: 参考位置(0:开头, 1:当前位置, 2:结尾)
with open('example.txt', 'r') as file:
# 读取前10个字符
print(file.read(10))
# 显示当前指针位置
print("当前指针位置:", file.tell())
# 移动指针到开头
file.seek(0)
# 读取第一行
first_line = file.readline()
print("第一行:", first_line.strip())
# 移动到文件末尾并追加数据
with open('example.txt', 'a+') as file:
file.seek(0, 2) # 移动到末尾
file.write("\n追加的新内容\n")
异常处理
文件操作中常见的异常处理方法。
try:
with open('nonexistent_file.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("错误:文件不存在")
except PermissionError:
print("错误:没有文件访问权限")
except IOError as e:
print(f"文件操作错误: {e}")
# 使用else和finally
try:
file = open('example.txt', 'r')
content = file.read()
except IOError:
print("文件读取失败")
else:
print("文件内容长度:", len(content))
finally:
file.close() # 确保文件关闭
文件编码处理
处理不同编码的文本文件。
# 写入UTF-8编码的文件
with open('utf8_text.txt', 'w', encoding='utf-8') as file:
file.write("你好,世界!\n")
file.write("Hello, World!\n")
# 读取UTF-8编码的文件
with open('utf8_text.txt', 'r', encoding='utf-8') as file:
for line in file:
print(line.strip())
# 处理GBK编码的文件
try:
with open('gbk_text.txt', 'r', encoding='gbk') as file:
content = file.read()
print(content)
except UnicodeDecodeError:
print("错误:文件编码不是GBK")
文件系统操作
使用`os`和`shutil`模块进行高级文件操作。
import os
import shutil
# 检查文件是否存在
if os.path.exists('example.txt'):
print("文件存在")
else:
print("文件不存在")
# 获取文件信息
file_info = os.stat('example.txt')
print("文件大小:", file_info.st_size, "字节")
# 重命名文件
os.rename('old_name.txt', 'new_name.txt')
# 删除文件
os.remove('unwanted_file.txt')
# 创建目录
os.makedirs('new_folder', exist_ok=True)
# 复制文件
shutil.copy('source.txt', 'destination.txt')
# 移动文件
shutil.move('source.txt', 'new_folder/source.txt')
总结
Python文件操作是编程中的基础技能,通过掌握`open()`函数的不同模式、`with`语句的安全使用、二进制文件处理、指针操作以及异常处理方法,可以高效地完成各种文件读写任务。实际应用中,建议优先使用`with`语句确保资源正确释放,并注意处理文件编码问题以避免乱码。对于更复杂的文件系统操作,可以结合`os`和`shutil`模块实现。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。







