zoukankan      html  css  js  c++  java
  • 作业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"))
    
  • 相关阅读:
    Nginx中如何配置中文域名?
    VS2012找不到EF框架实体模型的解决方法
    来自一位家长的电话
    孩子大了真是不好管了
    springboot项目不加端口号也可以访问项目的方法
    分享几个上机案例题
    今晚在学校值班……
    3班的第二次模拟面试
    Sword 09
    Sword 06
  • 原文地址:https://www.cnblogs.com/achai222/p/12507215.html
Copyright © 2011-2022 走看看