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)
  • 相关阅读:
    UVtool 工具解释1
    系统自己提供的 非常方便进行轴向的改变。
    解释脚本语言 计算两个向量的夹角度数。
    转换到正交视图的算法。
    对于 位 的判断我一般都转数组 其实这里有这个很好、
    服务器开启防火墙时千万别忘了开3389!
    j2me笔记
    成为那一小部分人!
    SEO笔记
    Java代码优化方案 J2ME内存优化
  • 原文地址:https://www.cnblogs.com/zhubincheng/p/12506831.html
Copyright © 2011-2022 走看看