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)
  • 相关阅读:
    IDEA右侧代码预览、代码地图消失(快捷键:Ctrl+Shift+g)
    vscode 清除多余空行
    StringJoiner
    redis远程连接
    el-container全屏布局(ElementUI)
    阿里云开启selinux无法启动系统问题
    fail模块场景(ansible)
    "***.sh" is read-only (add ! to override) 问题解决
    ansible 报错解决:ERROR! this task '****' has extra params, which is only allowed in the following modules:..
    java实现Excel定制导出(基于POI的工具类)
  • 原文地址:https://www.cnblogs.com/zhubincheng/p/12506831.html
Copyright © 2011-2022 走看看