文件操作
4.1 文件基本操作
1 obj = open('路径',mode='模式',encoding='编码') # 表示要干嘛 读 还是写 2 obj.write() #写什么内容 3 obj.read() #读到哪里,全读 4 obj.close()
4.2 打开模式
- r / w / a
- r+ / w+ / a+
- rb / wb / ab
- r+b / w+b / a+b
4.3 操作
- read() , 全部读到内存
- read(1)
- 1表示一个字符
1 obj = open('a.txt',mode='r',encoding='utf-8') 2 data = obj.read(1) # 1个字符 3 obj.close() 4 print(data)
1 obj = open('a.txt',mode='rb') 2 data = obj.read(3) # 1个字节 3 obj.close()
- write(字符串)
1 obj = open('a.txt',mode='w',encoding='utf-8') 2 obj.write('中午你') 3 obj.close()
- write(二进制)
1 obj = open('a.txt',mode='wb') 2 3 # obj.write('中午你'.encode('utf-8')) 4 v = '中午你'.encode('utf-8') 5 obj.write(v) 6 7 obj.close()
- seek(光标字节位置),无论模式是否带b,都是按照字节进行处理。
1 obj = open('a.txt',mode='r',encoding='utf-8') 2 obj.seek(3) # 跳转到指定字节位置 3 data = obj.read() 4 obj.close() 5 6 print(data) 7 8 obj = open('a.txt',mode='rb') 9 obj.seek(3) # 跳转到指定字节位置 10 data = obj.read() 11 obj.close() 12 13 print(data)
- tell(), 获取光标当前所在的字节位置
1 obj = open('a.txt',mode='rb') 2 # obj.seek(3) # 跳转到指定字节位置 3 obj.read() 4 data = obj.tell() #获取光标当前所在的字节位置 5 print(data) 6 obj.close()
- flush,强制将内存中的数据写入到硬盘
1 v = open('a.txt',mode='a',encoding='utf-8') 2 while True: 3 val = input('请输入:') 4 v.write(val) 5 v.flush() #这里flush已经把内容强行写进硬盘里了 6 7 v.close() #关闭文件、保存文件 2个功能
4.4 关闭文件
文艺青年
1 v = open('a.txt',mode='a',encoding='utf-8') 2 3 v.close()
二逼
1 with open('a.txt',mode='a',encoding='utf-8') as v: 2 data = v.read() # 错误 mode='a' 只能写,不能读 3 data=v.write() 4 # 缩进中的代码执行完毕后,自动关闭文件
4.5 文件内容的修改
1 with open('a.txt',mode='r',encoding='utf-8') as f1: 2 data = f1.read() 3 new_data = data.replace('飞洒','666') 4 5 with open('a.txt',mode='w',encoding='utf-8') as f1: 6 data = f1.write(new_data)
**大文件修改(一行一行读出来操作)**【创建】
1 f1 = open('a.txt',mode='r',encoding='utf-8') 2 f2 = open('b.txt',mode='w',encoding='utf-8') 3 for line in f1: #content= f1.readlines() 得到的是个列表,列表的元素是文件中每一行内容+换行符(字符串) 4 new_line = line.replace('阿斯','死啊') 5 f2.write(new_line) 6 f1.close() 7 f2.close()
1 with open('a.txt',mode='r',encoding='utf-8') as f1, open('c.txt',mode='w',encoding='utf-8') as f2: 2 for line in f1: 3 new_line = line.replace('阿斯', '死啊') 4 f2.write(new_line)