1、通用文件copy工具实现
inp_file = input("请输入需要复制文件的路径:").strip()
new_file = input("需要创建文件副本位置:").strip()
with open(rf"{inp_file}",mode="rb") as f,
open(rf"{new_file}",mode="wb") as f1:
while True:
res = f.read(1024)
if len(res) == 0:
break
f1.write(res)
2、基于seek控制指针移动,测试r+、w+、a+模式下的读写内容
# r+模式实现先读后写再读
with open("a.txt",mode="r+b") as f:
while True:
res = f.readline()
if not res:
break
print(res.decode("utf-8"),end="")
print()
f.write(b"12345
")
f.seek(0,0)
while True:
res = f.readline()
if not res:
break
print(res.decode("utf-8"), end="")
# r+模式实现先写后读
with open("a.txt",mode="r+b") as f:
f.seek(0,2) # 此处指针跳到末尾,不可使用t模式,只能使用b模式
# t模式下,只能seek函数只能使用模式0,即以文件开头为参照物
f.write(b"12345
")
f.seek(0) # 不设定模式,默认为0模式,即指针以文件头为参照物
while True:
res = f.readline()
if not res:
break
print(res.decode("utf-8"), end="")
#w+模式实现读写
with open("b.txt",mode="w+b") as f:
f.write(b"12345
")
f.seek(0,0)
while True:
res = f.readline()
if not res:
break
print(res.decode("utf-8"), end="")
# a+模式实现读写
with open("b.txt",mode="a+b") as f:
f.write("你妹!".encode("utf-8"))
f.seek(0,0)
# 指针移动的单位都是以bytes/字节为单位
# 只有一种情况特殊:
# t模式下的read(n),n代表的是字符个数
# f.seek(7,0) # 当取第七个字符时,中文字符编码被截断,将无法正确读取。'utf-8' codec can't decode byte 0xbd in position 0: invalid start byte
while True:
res = f.readline()
if not res:
break
print(res.decode("utf-8"), end="")
3、tail -f access.log程序实现
import time
with open("access.log",mode="a+b") as f:
while True:
line = f.readline()
if line:
print(line.decode("utf-8"),end="")
else:
time.sleep(0.05)