day---07 文件的操作


在rt模式下 read内的数字 表示的是字符的个数
除此之外,数字表示的都是字节



文件内光标的移动

f.seek(offset=,whence=) seek移动的时候都是字节
offset:相对变异量 光标移动的位数
whence:
0 : 参照文件开头
1 : 参照光标所在的当前位置
2 : 参照文件末尾

with open(r'E:程序第三周 ext','r+',encoding='utf-8') as f:
res =f.read()
print(res)
for line in res:
print(line)

其他模式补充
r
w
a
上面三个模式称为纯净模式
r+
w+
a+

with open(r'E:程序第三周 ext',mode = 'r+',encoding = 'utf-8') as f:
print(f.readable()) # True
print(f.writable()) # True
print(f.readline()) # egon哈哈哈哈哈,哈哈哈哈哈
f.write('嘿嘿嘿')

with open(r'E:程序第三周 ext',mode = 'w+',encoding = 'utf-8') as f:
print(f.readable()) # True
print(f.writable()) # True
print(f.readline()) # 嘿嘿嘿
f.write('嘿嘿嘿')

with open(r'E:程序第三周 ext',mode = 'r+b') as f:
print(f.readable()) # True
print(f.writable()) # True
res = f.read()
# print(res.decode('utf-8')) # 嘿嘿嘿
res1 = str(res,encoding='utf-8')
print(res1) # 嘿嘿嘿



在rt模式下read内的数字表示的是字符的个数
除此之外 数字表示的都是字节

with open(r'text','r',encoding='utf-8') as f:
print(f.read())

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

文件内光标的移动
with open(r'E:程序第三周 ext','rb') as f:
f.seek(offset,whence)
offset:相对偏移量
whence:
0 : 相对文件的开头 t和b都可以使用
1 : 参照光标所在的当前位置 只能在b模式下用
2 : 参照文件的莫问 只能在b模式下使用

with open(r'text','rt+',encoding = 'utf-8') as f:
print(f.read(1))
f.seek(6,0) # seek移动的都是字节数
f.write("略略略")
f.seek(4,0) # seek移动的都是字节数
print(f.read(1))
f.seek(0 ,0)
print(f.read(10))
f.seek(9 ,0)
print(f.read(1))
f.seek(6 ,0)
print(f.read())

with open(r'E:程序第三周 ext','rb') as f:
print(f.read())
f.seek(-12,2) # asdasdasd的 再强调一下 offset是字节 一个汉字代表三个bytes
print(f.read().decode('utf-8'))


with open(r'E:程序第三周 ext','r+',encoding='utf-8') as f:
f.seek(6,0)
f.write('你个锤锤')


写日志
import time # 导入时间模块
res = time.strftime('%Y-%m-%d %x')
print(res)
with open(r'E:程序第三周 ext','a',encoding='utf-8') as f:
f.write('%s xxx给了ooo发了1000W '%res) # 添加内容

检测文件内容
with open(r'text','rb') as f:
f.seek(0,2) # 将光标的位置移动在文件的末尾
while True:
res = f.readline()
# print(f.tell()) # fell 查看光标移动了多少bytes
if res:
print('增加的内容:%s'%res.decode('utf-8'))
else:
说明文件没人进行操作
print('文件无人操作')

截断文件
with open(r'text','a',encoding='utf-8') as f:
f.truncate(15) # 接受的字节的长度是整型
# 保留0-15字节数 后面的全部删除

修改文件(*************)
修改文件的两种方式
1
想把要更改的文件打开 从内存读到硬盘
将里面的需要替换的内容提替换掉
输出新的文件 新文件的内容将旧文件内容覆盖
with open(r'E:程序第三周 ext','r',encoding='utf-8') as f:
msg = f.read()
with open(r'E:程序第三周 ext','w',encoding='utf-8') as f:
res = msg.replace('james','egon')
f.write(res)

优点:任何时间硬盘上只有一个文件,占用空间少
缺点:当文件内容过大时,会造成文件溢出
2
创建一个新文件
对文件内容进行循环读取,读到内存后进行修改 将修改好的内容写到新文件里面
把把老文件删除 新文件名改成老文件名

import os
with open(r'E:程序第三周 ext','r',encoding='utf-8') as read_file,open(r'E:程序第三周 ew_text','a',encoding = 'utf-8') as write_file:
for line in read_file:
new_file = line.replace('egon','james')
write_file.write(new_file)
os.remove('text')
os.rename('new_text','text')
原文地址:https://www.cnblogs.com/xuzhaolong/p/11152423.html