#1、通用文件copy工具实现
src_file=input("请输入原文件路径>>") des_file=input("请输入原文件路径>>") with open(src_file,"rb") as f, open(des_file,"ab") as f_new: for i in f: f_new.write(i)
#2、基于seek控制指针移动,测试r+、w+、a+模式下的读写内容
#r+ with open("access.log","r+",encoding="utf-8") as f: print(f.tell()) #文件开始指针位置 f.write("hahaha") print(f.tell()) #写入操作后文件位置 f.seek(0,0) print(f.tell()) #指针移动到文件开头 #w+ with open("access.log","w+",encoding="utf-8") as f: print(f.tell()) #文件开始指针位置 f.write("hahaha") print(f.tell()) #写入操作后文件位置 f.seek(0,0) print(f.tell()) #指针移动到文件开头 #a+ with open("access.log","a+",encoding="utf-8") as f: print(f.tell()) #文件开始指针位置 f.write("hahaha") print(f.tell()) #写入操作后文件位置 f.seek(0,0) print(f.tell()) #指针移动到文件开头
#3、tail -f access.log程序实现
import os file_inp=input("请输入文件路径>>") if os.path.exists(file_inp): with open(file_inp,"rb") as f: f.seek(0,2) while True: line = f.readline() if line: print(line.decode("utf-8"),end="") else: print("{}文件不存在.".format(file_inp))