zoukankan      html  css  js  c++  java
  • python基础学习——文件操作的其他方法

    1、closed 判断文件是否关闭,关闭则返回True

    2、encoding,文件打开的编码方式

    3、flush刷新:将内存数据刷新到硬盘里

    4、tell:当前光标所在位置

      只要不是read方法,读取的是字符。其余的文件内光标移动都是以字节为单位

    f=open("肖战哥哥","r",encoding="utf-8",newline="") #读取文件中真正的换行符号
    print(f.tell())
    f.readline()
    print(f.tell())

    5、seek控制光标的移动

    f=open("肖战哥哥","r",encoding="utf-8",newline="")
    f.seek(3)
    print(f.tell())
    print(f.read())
    
    #方式二
    f=open("肖战哥哥","r",encoding="utf-8",newline="") 
    data=f.read(6)
    print(data)

      5.1 seek 补充

    f=open("肖战哥哥","rb") #读seek移动时,以二进制方式定义,二进制方式不需要encoding
    print(f.tell())
    f.seek(3,0)#默认光标从文件0开始移动,移动3个字节
    print(f.tell())
    f.seek(4,1)#1代表相对位置,从上一个位置,移动5个字节
    print(f.tell())
    
    #方式二
    f.seek(-5,2)#2代表从文件末尾开始移动光标,倒序移动5个字节
    print(f.tell())

    5.2 seek补充2,查看最近的日志

    f=open("肖战哥哥","rb")
    for i in f :
        offs=-10
        while True:
            f.seek(offs,2)
            data=f.readlines()
            if len(data)>1:
                print("文件最后一行是%s" %(data[-1].decode("utf-8")))
                break
            offs *=2

    6、truncate(9)截取文件,从文件开头开始算,9为字节数

      文件以写的模式打开,但是不能是w或者w+模式

  • 相关阅读:
    iptables 常用命令解析
    iptables 常用处理动作
    centos7 中iptables、firewalld 和 netfilter 的关系
    iptables 的几个状态
    centos7 中没有service iptables save指令来保存防火墙规则
    iptables 数据走向流程
    数据库PDO简介
    php连接mySql,加密函数
    php数组,常量,遍历等
    php的会话控制
  • 原文地址:https://www.cnblogs.com/xucuiqing/p/11717158.html
Copyright © 2011-2022 走看看