第四章文件操作
第四章 文件操作
4.1 文件基本操作
obj = open('路径',mode='模式',encoding='编码') obj.write() obj.read() obj.close() with open...
4.2 打开模式
- r / w / a
- r+ / w+ / a+
- rb / wb / ab
- r+b / w+b / a+b
4.3 操作
-
read() , 全部读到内存
-
read(1)
-
1表示一个字符
obj = open('a.txt',mode='r',encoding='utf-8') data = obj.read(1) # 1个字符 obj.close() print(data) -
1表示一个字节
obj = open('a.txt',mode='rb') data = obj.read(3) # 1个字节 obj.close()
-
-
write(字符串)
obj = open('a.txt',mode='w',encoding='utf-8') obj.write('中午你') obj.close() -
write(二进制)
obj = open('a.txt',mode='wb') # obj.write('中午你'.encode('utf-8')) v = '中午你'.encode('utf-8') obj.write(v) obj.close() -
seek(光标字节位置),无论模式是否带b,都是按照字节进行处理。
obj = open('a.txt',mode='r',encoding='utf-8') obj.seek(3) # 跳转到指定字节位置 data = obj.read() obj.close() print(data) obj = open('a.txt',mode='rb') obj.seek(3) # 跳转到指定字节位置 data = obj.read() obj.close() print(data) -
tell(), 获取光标当前所在的字节位置
obj = open('a.txt',mode='rb') # obj.seek(3) # 跳转到指定字节位置 obj.read() data = obj.tell() print(data) obj.close() -
flush,强制将内存中的数据写入到硬盘
v = open('a.txt',mode='a',encoding='utf-8') while True: val = input('请输入:') v.write(val) v.flush() v.close()
4.4 关闭文件
文艺青年
v = open('a.txt',mode='a',encoding='utf-8') v.close()
二逼
with open('a.txt',mode='a',encoding='utf-8') as v: data = v.read() # 缩进中的代码执行完毕后,自动关闭文件
4.5 文件内容的修改
with open('a.txt',mode='r',encoding='utf-8') as f1: data = f1.read() new_data = data.replace('飞洒','666') with open('a.txt',mode='w',encoding='utf-8') as f1: data = f1.write(new_data)
大文件修改
f1 = open('a.txt',mode='r',encoding='utf-8') f2 = open('b.txt',mode='w',encoding='utf-8') for line in f1: new_line = line.replace('阿斯','死啊') f2.write(new_line) f1.close() f2.close()
with open('a.txt',mode='r',encoding='utf-8') as f1, open('c.txt',mode='w',encoding='utf-8') as f2: for line in f1: new_line = line.replace('阿斯', '死啊') f2.write(new_line)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)