文件操作
1 文件的基本操作
jj = open('路径',mode='模式',encoding='编码')
jj.write()#写入
jj.read()#读取全部
jj.close()#关闭文件
2 打开模式
2.1 r / w / a 只读只写
r是只读,w是只写(先清空文件),a是只写(只添加不能读)
2.2 r+ / w+ / a+ 可读可写
r+ (**)常用程度
读:,默认光标位置0,读时默认从最开始读
写:根据光标的位置从当前光标位置开始进行操作,会覆盖当前光标后面的值
w+ (**)常用程度
读:默认光标最后或0,读取时需要调整光标位置
写:先清空
a+ (*)常用程度
读:默认光标位置在最后,读需要调整光标位置
写:写入时不论怎么调整光标位置,永远写到最后
2.3 rb / wb / ab 只读只写(二进制)
rb是只读(以二进制读取),wb是只写(以二进制写入),ab是(以二进制追加)
2.4 r+b / w+b / a+b 可读可写(二进制)
rb+(二进制) (**)常用程度
读:,默认光标位置0,读时默认从最开始读
写:根据光标的位置从当前光标位置开始进行操作,会覆盖当前光标后面的值
wb+(二进制) (**)常用程度
读:默认光标最后或0,读取时需要调整光标位置
写:先清空
ab+(二进制) (*)常用程度
读:默认光标位置在最后,读需要调整光标位置
写:写入时不论怎么调整光标位置,永远写到最后
3 操作
3.1 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()
3.2 write
- 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()
3.3 seek(光标字节位置)
-
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)
3.4 tell(), 获取光标当前位置
-
tell(), 获取光标当前所在的字节位置
obj = open('a.txt',mode='rb') # obj.seek(3) # 跳转到指定字节位置 obj.read() data = obj.tell() print(data) obj.close()
3.5 flush(刷新)
-
flush,强制将内存中的数据写入到硬盘
v = open('a.txt',mode='a',encoding='utf-8') while True: val = input('请输入:') v.write(val) v.flush() v.close()
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()
# 缩进中的代码执行完毕后,自动关闭文件
5 文件内容的修改
5.1 普通文件修改
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)
5.2 大文件修改
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)