Python文件操作基础
在Python中,文件操作是处理数据存储和读取的基础功能。通过内置的open()
函数,我们可以轻松地操作文本文件和二进制文件。
核心概念:
- 文件路径 - 可以是绝对路径或相对路径
- 打开模式 - 读取(r)、写入(w)、追加(a)、二进制(b)等
- 文件对象 - open()函数返回的文件对象用于各种操作
- 编码 - 特别是文本文件,需指定正确的编码(如UTF-8)
打开文件的基本语法:
file = open('filename.txt', 'r', encoding='utf-8')
多种文件读取方法
Python提供了多种读取文件内容的方法,适用于不同场景:
1. read() - 读取整个文件
with open('example.txt', 'r') as file: content = file.read() print(content)
适用于小文件,一次性读取全部内容到内存中。
2. readline() - 逐行读取
with open('example.txt', 'r') as file: line = file.readline() while line: print(line, end='') line = file.readline()
适用于需要逐行处理的场景,内存效率高。
3. readlines() - 读取所有行
with open('example.txt', 'r') as file: lines = file.readlines() for line in lines: print(line, end='')
返回行列表,适合需要随机访问行内容的场景。
4. 遍历文件对象
with open('example.txt', 'r') as file: for line in file: print(line, end='')
最简洁高效的方法,推荐用于大型文件处理。
文件写入操作
Python提供了多种文件写入方式,根据需求选择不同模式:
写入模式('w')
with open('output.txt', 'w') as file: file.write('第一行内容\n') file.write('第二行内容\n')
创建新文件或覆盖现有文件内容。
追加模式('a')
with open('log.txt', 'a') as file: file.write('新的日志条目\n')
在文件末尾追加内容,不覆盖原有数据。
读写模式('r+')
with open('data.txt', 'r+') as file: content = file.read() file.seek(0) file.write('更新的内容\n' + content)
同时支持读取和写入操作,文件指针位置需特别注意。
使用上下文管理器(with语句)
上下文管理器是处理文件操作的最佳方式,能自动管理资源并处理异常:
上下文管理器的优势:
- 自动关闭文件 - 确保文件被正确关闭,即使在发生异常时
- 代码简洁 - 减少样板代码,提高可读性
- 资源安全 - 防止文件描述符泄漏
基本用法:
with open('example.txt', 'r') as file: # 在此执行文件操作 data = file.read() # 离开with块后文件自动关闭
同时处理多个文件:
with open('source.txt', 'r') as src, open('destination.txt', 'w') as dest: content = src.read() dest.write(content.upper())
文件操作最佳实践
1. 始终使用with语句
避免手动关闭文件可能导致的资源泄漏问题。
2. 明确指定编码
特别是处理非英文字符时:
with open('file.txt', 'r', encoding='utf-8') as f: ...
3. 处理大文件
使用迭代方法避免内存问题:
with open('large_file.txt', 'r') as f: for line in f: process_line(line)
4. 异常处理
处理文件操作中可能出现的错误:
try: with open('file.txt', 'r') as f: content = f.read() except FileNotFoundError: print("文件不存在") except PermissionError: print("没有访问权限") except Exception as e: print(f"发生错误: {str(e)}")
发表评论