day 7

it2022-05-05  164

文件操作

1.r(只读模式)

2.w(只写模式)

3.a(追加模式)

以上为纯净模式

1.r+

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

2.w+

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

3.a+

4.r+b

with open(r'tst',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)

文件光标的移动

1.在rt模式下,read内的数字表示的是字符的个数

文件内光标的移动

''' f.seek(offset,whence) offst:相对偏移量 光标移动的位数 whence: 0.参照文件的开头 t和b都可以使用 1.参照光标所在的当前位置 只能在b模式下用 2.参照文件的末尾 只能在b模式下用 ''' with open(r'tst','r',encoding='utf-8') as f: print(f.read(1)) f.seek(6.0) #seek移动都是字节数 f.seek(4,0) #seek移动都是字节数 with open(r'tst','rb',encoding='utf-8') as f: print(f.read(3).decode('utf-8')) f.seek(0,0) print(f.read(1).decode('utf-8') f.seek(6,0) #移动的都是字节数 with open (r'tst','rb') as f: print(f.read()) f.seek(-4,2) print(f.read().decode('utf-8')) with open (r'tst','r+','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'tst','a',encoding='utf-8') as f: f.write('%s egon给jason发了一块钱'%res)

检测内容

with open(r'tst','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'tst','a',encoding='utf-8') as f: f.truncate(6) #接收的字节的长度 整型 #保留0~6字节 后面的全被删除(截断)

 

转载于:https://www.cnblogs.com/KrisYzy/p/11151334.html


最新回复(0)