Python 文件操作详解
从创建到关闭,一文搞懂文件操作全流程
在编程工作中文件操作还是比较常见的,基本文件操作包括:创建、读、写、关闭等。Python 中内置了一些文件操作函数,我们使用 Python 操作文件还是很方便的。
Python 文件操作的核心流程可以概括为:打开 → 操作 → 关闭。整个过程围绕 open() 函数展开。
| | |
|---|
| | |
| | |
| read() / readline() / readlines() | |
| | |
| | |
Python 使用 open() 函数创建或打开文件,语法格式如下:
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
| |
|---|
| |
| |
| |
| |
| 指定如何处理编码和解码错误(不能在二进制模式下使用) |
| |
| 为 False 且给出文件描述符时,关闭时底层描述符保持打开;默认 True |
| |
mode 可选模式如下:
以 txt 格式文件为例,我们不手动创建文件,通过代码方式来创建:
open('test.txt', mode='w', encoding='utf-8')
执行完上述代码,就为我们创建好了 test.txt 文件。
⚠️ 踩坑经验
使用 'w' 模式时,如果文件已存在会被截断(清空)!如果只是想追加内容,请使用 'a' 模式。
对于写操作,Python 文件对象提供了两个函数:
wf = open('test.txt', 'w', encoding='utf-8')wf.write('Tom\n')wf.writelines(['Hello\n', 'Python'])# 关闭wf.close()
💡 小贴士
如果打开的文件忘记了关闭,可能会对程序造成一些隐患(如资源泄露、数据未刷盘)。推荐使用 with as 语句,程序执行完成后会自动关闭已经打开的文件:
with open('test.txt', 'w', encoding='utf-8') as wf: wf.write('Tom\n') wf.writelines(['Hello\n', 'Python'])
🔑 关键要点
① write() 返回写入的字符长度,可以用来验证写入是否完整② writelines() 不会自动添加换行符,需要手动在字符串中加 \n③ 始终使用 with 语句管理文件,避免忘记关闭
04读取read / readline / readlines对于文件的读操作,Python 文件对象提供了三个函数:
| |
|---|
| 读取指定的字节数,参数可选,无参或参数为负时读取所有 |
| |
| |
with open('test.txt', 'r', encoding='utf-8') as rf: print('readline-->', rf.readline()) print('read-->', rf.read(6)) print('readlines-->', rf.readlines())
readline--> Tomread--> Helloreadlines--> ['Python']
⚠️ 踩坑经验
文件对象是迭代式的,读取后指针会移动。连续调用不同读取函数时,要注意当前指针位置——上一次读取到哪里,下一次就从哪里继续,不会自动回到开头。
Python 提供了两个与文件对象位置相关的函数:
seek 参数说明:
with open('test.txt', 'rb+') as f: f.write(b'123456789') # 文件对象位置 print(f.tell()) # 9 # 移动到文件的第四个字节 f.seek(3) # 读取一个字节,文件对象向后移动一位 print(f.read(1)) # b'4' print(f.tell()) # 4 # 移动到倒数第二个字节 f.seek(-2, 2) print(f.tell()) # 7 print(f.read(1)) # b'8'
💡 小贴士
seek() 在文本模式('t')下仅支持从文件开头(whence=0)定位;二进制模式('b')下三种参考点都可用。需要灵活定位时,记得用二进制模式打开。
除了上面那些函数,Python 文件对象还有一些其他方法,如 isatty() 和 truncate(),虽然出场率较低,但了解它们在某些场景下会很有帮助。
🔍 isatty()
检测文件对象是否连接到终端设备,返回布尔值。普通文件返回 False。
✂️ truncate(size)
截取文件到指定字节数。如果不传参数,则截取到当前指针位置。
Python - isatty 与 truncatewith open('test.txt', 'r+') as f: # 检测文件对象是否连接到终端设备 print(f.isatty()) # False # 截取两个字节 f.truncate(2) print(f.read())
在自动化测试中,文件操作常用于读写配置、保存测试数据、生成报告等场景。下面是一个实用示例:
import jsonclass TestDataManager: """测试数据文件管理器""" def __init__(self, filepath): self.filepath = filepath def read_test_data(self): """读取测试数据""" with open(self.filepath, 'r', encoding='utf-8') as f: return json.load(f) def write_test_data(self, data): """写入测试数据""" with open(self.filepath, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) def append_log(self, log_line): """追加日志""" with open(self.filepath, 'a', encoding='utf-8') as f: f.write(log_line + '\n')# 使用manager = TestDataManager('testdata.json')manager.write_test_data({'username': 'admin', 'password': '123456'})data = manager.read_test_data()print(data) # {'username': 'admin', 'password': '123456'}
💡 给测试工程师的建议
1. 用 with 语句管理文件:自动关闭,避免资源泄露2. 始终指定 encoding:encoding='utf-8' 防止跨平台编码问题3. 用 'a' 模式追加日志:不要用 'w' 模式写日志,会清空历史记录4. 大文件用 readline 逐行读:避免 read() 一次性加载到内存
| | |
|---|
| | |
| | |
| read() / readline() / readlines() | |
| | |
| | |
在实际开发中,最常用的是 with open() as f 的写法,它既能自动管理资源,又简洁优雅。建议日常编码中养成使用 with 语句的习惯,从根源上避免文件资源泄露的问题!
Python 学习笔记系列 | 第十二篇