• python文件处理指针的移动


    控制文件指针移动

    with open('a.txt',mode='rt',encoding='utf-8')as f:
        res=f.read(4)
        print(res)

    强调:只有t模式下read(n)中的n表示的是字符个数,其他都是以字节为单位。

    with open('a.txt',mode='rb')as f:
        res=f.read(3)
        print(res.decode('utf-8'))
    f.seek():指针移动    以字节为单位

    三种模式:

    • 0(默认):参照文件开头

    • 1                :参照指针当前位置

    • 2                :参照文件末尾

    I 0模式:参照文件开头

          只有0模式既可在t下用也可在b模式下用。1.2只能在b模式下用

    with open('a.txt',mode='rt',encoding='utf-8') as f:
        f.seek(3, 0)
        print(f.tell()) #显示指针位置
        print(f.read())
    #参照文件开头指针位置向后移动3个字节

    II 1模式:参照指针当前位置

    with open('a.txt',mode='rb')as f:
        f.read(3) #先读三个字节,指针移动到3
        f.seek(3, 1)#1以指针当前位置再移动3位
        print(f.read().decode('utf-8'))

    III 2模式:参照文件末尾

    with open('a.txt',mode='rb')as f:
        f.seek(-5,2) #参照文件末尾,指针移动到-5
        print(f.tell())
        print(f.read().decode('utf-8'))

    小练习:

    写一个程序监测文件中新增内容:

    with open('access.log',mode='at',encoding='uft-8')as f:
        f.write('时间  内容 登陆名
    ')  #先写一个程序:该程序就是被监测程序
    import time  #导入时间模块,刷新时间
    with open('access.log',mode='rb')as f:
        f.seek(0, 2)  #将指针移到文件末尾
        while True:   #循环一行行读取文件
            line = f.readline()
            if len(line) == 0:#判断文件长度是否为0,为0表示文件未写入
                time.sleep(1)
            else:#如果有文件写入则会打印
                print(line.decode('utf-8'), end='')
  • 相关阅读:
    use evolation+mapi with exhange mode
    python open file mode description
    5 reasons why you should learn python programming
    文本从尾到头输出
    安装部署lamp,来测试rediect
    python for ,loop ,else condition test
    python logging usage
    去除重复行
    [WTL]WTL for MFC Programming实践篇 一个自定义ComboBox的移植过程
    subsonic已死,db4o将死
  • 原文地址:https://www.cnblogs.com/5j421/p/10027668.html
Copyright © 2020-2023  润新知