作业8

1、通用文件copy工具实现

old_file = input("请输入被拷贝的文件的绝对路径:")
new_file = input("请输入拷贝出的文件保存的绝对路径:")
with open(old_file, mode="rb") as f1, open(new_file, mode="wb") as f2:
    for line in f1:
        f2.write(line)

2、基于seek控制指针移动,测试r+、w+、a+模式下的读写内容

# w+b 模式
# 初始情况:空
# w+b模式写操作时会按指针覆盖
with open("b.txt", mode="w+b") as f:
    f.write("哈哈
嘿嘿
喔喔
".encode("utf-8"))
    # 在嘿嘿
后写嘎嘎
,猜测会在喔喔前添加嘎嘎,但是发现覆盖了喔喔

    f.seek(-7, 2)
    f.write(bytes("嘎嘎
", "utf-8"))
    # 读嘿嘿嘎嘎
    f.seek(7, 0)
    res = f.read()
    print(res)
    print(res.decode("utf-8"))
    # 读嘿嘿嘎嘎
    f.seek(-14, 1)
    res = f.read()
    print(res)
    print(res.decode("utf-8"))
# a+b模式
# 初始情况:哈哈嘿嘿嘎嘎
# a+b写操作时指针自动跳到最后
with open("b.txt", mode="a+b") as f:
    # 在哈哈
嘿嘿
嘎嘎
后写哦哦

    f.write("哦哦
".encode("utf-8"))
    f.seek(-7, 1)
    # 在嘎嘎
后写嘎嘎
,猜测会覆盖哦哦
,结果指针未变,依旧在最后写入
    f.write(bytes("嘎嘎
", "utf-8"))
    # 读哈嘿嘿嘎嘎哦哦嘎嘎
    f.seek(3, 0)
    res = f.read()
    print(res)
    print(res.decode("utf-8"))
    # 读哦哦嘎嘎
    f.seek(-14, 2)
    res = f.read()
    print(res)
    print(res.decode("utf-8"))

# r+b模式
# 初始情况:哈哈嘿嘿嘎嘎哦哦嘎嘎
# 写会覆盖,初始指针在开头
with open("b.txt", mode="r+b") as f:
    f.write(b"t21")
    f.seek(-7, 2)
    f.write(b"123aabs")
    f.seek(3, 0)
    res = f.read()
    print(res)
    print(res.decode("utf-8"))
    f.seek(-14, 2)
    res = f.read()
    print(res)
    print(res.decode("utf-8"))
# t21哈
# 嘿嘿
# 嘎嘎
# 哦哦
# 123aabs

3、tail -f access.log程序实现


# 新增行的数据记录

with open("test.txt", mode="rb") as f:
    f.seek(0, 2)
    seat = f.tell()
print(seat)

with open("test.txt", mode="ab") as f:
    f.write("新增内容".encode("utf-8"))

with open("test.txt", mode="rb") as f:
    f.seek(seat, 0)
    while 1:
        res = f.readline()
        if res == b"":
            break
        print(res)
        print(res.decode("utf-8"))
原文地址:https://www.cnblogs.com/achai222/p/12507215.html