• day12 作业


    1、通用文件copy工具实现

    with open("a.txt","r",encoding="utf-8") as f ,open("b.txt","w",encoding="utf-8") as f1:
        f1.write(f.read())
    

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

    r+

    with open("b.txt","r+",encoding="utf-8") as f :
        print(f.read())#输出文件全部内容,此时光标到末尾
        f.seek(5,0)#把光标移动到第5个字节处
        print(f.tell())
        f.write("bbb")#覆盖原来的aaa为bbb,此时光标到第8个字节处
        print(f.read())#从第8个字节读取剩余文件内容
    

    w+

    with open("b.txt","w+",encoding="utf-8") as f :
        print(f.read())#w模式先会将文件清空,此时读不到文件,光标在开头
        f.seek(5,0)#把光标移动到第5个字节处
        print(f.tell())
        f.write("bbb")#从第5个字节处写入bbb此时光标到第8个字节处
        print(f.read())#从第8个字节读取剩余文件内容
    

    a+

    with open("b.txt","a+",encoding="utf-8") as f :
        print(f.read())#a模式先会将光标移动到文件末尾,此时读不到文件内容
        f.seek(5,0)#把光标移动到第5个字节处
        print(f.tell())
        f.write("bbb")#a模式在写入文件内容时会默认把光标移动到文件末尾
        print(f.read())#从文件末尾读取剩余文件内容
    

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

    import time
    with open("b.txt","rb")as f :
        f.seek(0,2)
        while True:
            line = f.readline()
            if len(line)==0:
                time.sleep(1)
            else:
                print(line.decode("utf-8"))
    #新建另外一个py文件
    with open("b.txt","a")as f:#先执行
        f.write("aaaa")
    
  • 相关阅读:
    python基础之列表解析
    初学者学习python2还是python3?
    给曾经是phper的程序员推荐个学习网站
    详解python2 和 python3的区别
    Python如何进行中文注释
    import方法引入模块详解
    详解python 局部变量与全局变量
    131-19. 删除链表的倒数第N个节点
    65.django中关于跨域访问设置
    130-283. 移动零
  • 原文地址:https://www.cnblogs.com/hz2lxt/p/12503890.html
Copyright © 2020-2023  润新知