1.通用文件copy工具实现
src_file = input('原文件路径:').strip()
dst_file = input('新文件路径:').strip()
with open(r'{}'.format(src_file),mode='rb') as f1,\
open(r'{}'.format(dst_file),mode='wb') as f2:
res = f1.read()
f2.write(res)
2.基于seek控制指针移动,测试r+、w+、a+模式下的读写内容
r+
with open(r'b.txt',mode='r+t',encoding='utf-8') as f:
print(f.read()) # 打印b.txt中的内容,内容为:123456789,光标会移至末尾
f.seek(5,0) # 将指针移到第5个字符
print(f.tell()) # 打印当前指针位置,为5
f.write('qwe') # 写入qwe,替换6-8个字符
f.seek(0, 0) # 再将指针移到开头
print(f.read()) # 再次打印b.txt中的内容,内容为:12345qwe9
w+
with open(r'b.txt',mode='w+t',encoding='utf-8') as f:
print(f.read()) # w模式会清空文件的内容,此时打印内容为空,指针在开头
f.seek(10,0) # 将指针移到第10个字符
print(f.tell()) # 打印当前指针位置,为10
f.write('qwe') # 写入qwe,替换11-13个字符
f.seek(0, 0) # 再将指针移到开头
print(f.read()) # 再次打印b.txt中的内容,内容为: qwe
a+
with open(r'b.txt',mode='a+t',encoding='utf-8') as f:
print(f.read()) # a模式不会清空文件的内容,指针在末尾
f.seek(5,0) # 将指针移到第5个字符
print(f.tell()) # 打印当前指针位置,为5
f.write('qwe') # 写入qwe,会在末尾写入qwe
f.seek(0, 0) # 再将指针移到开头
print(f.read()) # 再次打印b.txt中的内容,内容为:123456789qwe
3.tail -f access.log程序实现
while 1:
print('输入任意文字可添加至日志,输入readlog可读取日志信息')
msg = input('输入指令:').strip()
if msg == 'readlog':
with open(r'access.log', 'a+b') as f:
f.write(bytes('{}\n'.format(msg), encoding='utf-8'))
f.seek(0, 0)
log = f.read().decode('utf-8')
print(log)
continue
else:
with open(r'access.log', 'ab') as f:
f.write(bytes('{}\n'.format(msg), encoding='utf-8'))