x模式、b模式、文件其他操作、指针移动练习

#1、通用文件copy工具实现
'''
file1=input('文件路径: ').strip()
file2=input('文件路径: ').strip()
with open(r'{}'.format(file1),mode='rb') as f1,open(r'{}'.format(file2),mode='wb') as f2:
for line in f1:
f2.write(line)
'''
#2、基于seek控制指针移动,测试r+、w+、a+模式下的读写内容
'''
with open('user.txt',mode='rt+',encoding='utf-8') as f:
f.seek(9,0)
f.seek(3,0)
print(f.tell())
cmd=f.read()
print(cmd)
with open('user.txt',mode='w+t',encoding='utf-8') as f:
f.seek(9,0)
f.seek(3,0)
print(f.tell())
cmd=f.write('哈哈哈 ')
print(cmd)
with open('user.txt',mode='a+t',encoding='utf-8') as f:
f.seek(9,0)
f.seek(3,0)
print(f.tell())
cmd=f.write('哈哈哈 ')
print(cmd)

with open('user.txt',mode='rb+') as f:
f.seek(9,1)
f.seek(3,1)
print(f.tell())
cmd=f.read()
print(cmd.decode('utf-8'))
with open('user.txt',mode='w+b') as f:
f.seek(9,1)
f.seek(3,1)
print(f.tell())
cmd=f.write('哈哈哈 '.encode('utf-8'))
print(cmd)
with open('user.txt',mode='a+b') as f:
f.seek(9,1)
f.seek(3,1)
print(f.tell())
cmd=f.write('哈哈哈 '.encode('utf-8'))
print(cmd)

with open('user.txt',mode='rb+') as f:
f.seek(-9,2)
f.seek(-3,2)
print(f.tell())
cmd=f.read()
print(cmd.decode('utf-8'))
with open('user.txt',mode='w+b') as f:
cmd=f.write('哈哈哈 '.encode('utf-8'))
cmd1=f.write('哈哈哈 '.encode('utf-8'))
f.seek(-9,2)
print(f.tell())
print(f.read().decode('utf-8'))
with open('user.txt',mode='a+b') as f:
f.seek(-9,2)
f.seek(-3,2)
print(f.tell())
cmd=f.write('哈哈哈 '.encode('utf-8'))
print(cmd)
'''
#3、tail -f access.log程序实现
'''
import time
with open('user.txt',mode='rb') as f:
f.seek(0,2)
while True:
i=f.read()
if len(i) == 0:
time.sleep(0.5)
else:
print(i.decode('utf-8'),end='')
'''
原文地址:https://www.cnblogs.com/0B0S/p/12505142.html