zoukankan      html  css  js  c++  java
  • 3.15---文件处理练习2

    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)
  • 相关阅读:
    【计算机世界】467- XOR — 神奇的按位运算符
    记 · 复习知识 · 偶遇好玩的知识点
    【CSS】466- 一行 CSS 代码搞定响应式布局
    【Web技术】465- 关于前端埋点统计方案思考
    【CSS】464- 5种 CSS 浮动和清除浮动的方法
    简单易懂的 React useState() Hook 指南(长文建议收藏)
    java中的四类八种
    线程
    异常
    Aspx Ajax 调用 C#函数处理数据
  • 原文地址:https://www.cnblogs.com/zhubincheng/p/12506831.html
Copyright © 2011-2022 走看看