文件处理模式

其他模式补充

1、r 只读模式/

2、w 只写模式

3、追加写模式

将上面的三个模式称为纯净模式
r+
w+
a+

"""

with open(r'test',mode='r+',encoding='utf-8') as f:
print(f.readable())
print(f.writable())
print(f.readline())
f.write('嘿嘿嘿')

 

with open(r'test',mode='w+',encoding='utf-8') as f:
print(f.readable())
print(f.writable())
print(f.readline())
f.write('嘿嘿嘿')

  

with open(r'test',mode='r+b') as f:
print(f.readable())
print(f.writable())
res = f.read()
print(res.decode('utf-8'))
res1 = str(res,encoding='utf-8')
print(res1)

 

在rt模式下 read内的数字 表示的是字符的个数
除此之外,数字表示的都是字节
with open(r'test','r',encoding='utf-8') as f:
print(f.read(5))

with open(r'test','rb') as f:
res = f.read(10) # 读的是三个字节bytes
print(res)
print(res.decode('utf-8'))文件内光标的移动

"""
f.seek(offset,whence)
offset:相对偏移量 光标移动的位数
whence:
0:参照文件的开头 t和b都可以使用
1:参照光标所在的当前位置 只能在b模式下用
2:参照文件的末尾 只能在b模式下使用
"""
with open(r'test','rt',encoding='utf-8') as f:
print(f.read(1))
# f.seek(6,0) # seek移动都是字节数
# f.seek(4,0) # seek移动都是字节数
# print(f.read(1))
f.seek(0,0)
print(f.read(1))
f.seek(0, 0)
print(f.read(1))
f.seek(6,0)
print(f.read())

 

with open(r'test','rb') as f:
print(f.read(3).decode('utf-8'))
f.seek(0,0)
print(f.read(3).decode('utf-8'))
f.seek(7,0)
print(f.read(1).decode('utf-8'))
# f.seek(6,0) # seek移动都是字节数
# f.seek(4,0) # seek移动都是字节数

with open(r'test','rb') as f:
print(f.read(3).decode('utf-8'))
f.seek(3,1)
print(f.read(1))
f.seek(6,0) # seek移动都是字节数
f.seek(4,0) # seek移动都是字节数


with open(r'test','rb') as f:
print(f.read())
f.seek(-4,2)
print(f.read().decode('utf-8'))

with open(r'test','r+',encoding='utf-8') as f:
f.seek(3,0)
f.write('过')

import time
res = time.strftime('%Y-%m-%d %X')
print(res,type(res))

with open(r'test01.txt','a',encoding='utf-8') as f:
f.write('%s egon给jason发了1个亿的工资\n'%res)with open(r'test01.txt','rb') as f:

先将光标移动到文件末尾
f.seek(0,2)
while True:
res = f.readline()
查看光标移动了多少位 bytes
print(f.tell())
if res:
print("新增的文件内容:%s"%res.decode('utf-8'))
说明有人操作当前文件
else:
说明文件没有被任何人操作
print('暂无其他人操作该文件')

with open(r'test','a',encoding='utf-8') as f:
f.truncate(6) # 接收的字节的长度 整型
# 保留0~6字节数 后面的全部删除(截断)

 

with open(r'test','r+',encoding='utf-8') as f:
f.seek(6,0)
f.write('h')

 

修改文件
先将数据由硬盘读到内存(读文件)
在内存中完成修改(字符串的替换)
再覆盖原来的内容(写文件)

with open(r'test02.txt','r',encoding='utf-8') as f:
data = f.read()
print(data)
print(type(data))

with open(r'test02.txt','w',encoding='utf-8') as f:
res = data.replace('egon','jason')
print(data)
f.write(res)

  

"""
优点:任意时间硬盘上只有一个文件 不会占用过多硬盘空间
缺点:当文件过大的情况下,可能会造成内存溢出
"""


# 文件修改方式2
# 创建一个新文件
# 循环读取老文件内容到内存进行修改 将修改好的内容写到新文件中
# 将老文件删除 将新文件的名字改成老文件名
import os

 

with open(r'test02.txt','r',encoding='utf-8') as read_f,\
open(r'test02.swap','a',encoding='utf-8') as write_f:
for line in read_f:
new_line = line.replace('jason','egon')
write_f.write(new_line)
os.remove('test02.txt')
os.rename('test02.swap','test02.txt')

 

"""
优点:内存中始终只有一行内容 不占内存
缺点:再某一时刻硬盘上会同时存在两个文件

posted @ 2019-07-08 20:45  Aomur  阅读(195)  评论(0编辑  收藏  举报