zoukankan      html  css  js  c++  java
  • 文件进阶

    t 模式:

    • 读,写都以字符串为单位
    • 文本文件
    • 必须指定 encoding 格式  

    b 模式:

    • 读,写都以直接为单位
    • 针对所有文件
    • 不必须指定 encoding 格式 

    t 模式和b 模式::

    • 文本文件使用t 模式
    • 针对所有文件使用b 模式
    #t模式读取文本
    with open(r"aaa","rt",encoding="utf-8") as f:
        res =f.read()
        print(res)
    
    #b模式可以读图片
    with open("白人像3-1.jpg","rb") as f:
        res =f.read()
        print(res)

    读文件的其他方式:

    • read:一次性读取
    • readline:一次读取一行
    • readlines:读取所有行
    • read 和 readlines 的局限性:不适合读取文件量大的文件,如果读取的量过多会溢出内存。

    写文件的其他方式:

    • writelines
    with open(r"aaa","wb") as f:
        l = [b"aaa
    ",b"bbb
    ",b"ccc"] #加b = encoding 解码
        f.writelines(l)
    
    
    with open(r"aaa","wb") as f:
        l = [bytes("小花花
    ",encoding="utf-8"),
             bytes("小灰灰",encoding="utf-8")] # 字节---> 字符
        f.writelines(l)
    
    with open(r"aaa","wb") as f:
        l =[bytes("小灰灰",encoding="utf-8")]
        f.writelines(l)
        f.flush()#用于调试

    指针移动以bytes为单位。

      seek(n,模式),n表示字节个数

      模式:

      • 0,参照物文件开头位置
      • 1,参照文件当前位置
      • 2,参照文件末尾位置,倒着移动
    • 强调:只有0模式可以在t模式使用,1,2模式可以在b模式使用
    #0
    with open('aaa.txt',mode='rb') as f: f.seek(4,0) res=f.read() print(res.decode('utf-8'))
    #1
    with open('aaa.txt',mode='rb') as f:
    f.seek(9,1)
    print(f.tell())#tell表示指针当前的位置

    #2
    with open('aaa.txt',mode='rb') as f:
    f.seek(-3,2)
    print(f.read().decode('utf-8'))

    特殊情况:

      t 模式 read(n),n表示字符个数

     with open('aaa.txt','rt',encoding='utf-8') as f:
         res=f.read(4)
         print(res)
  • 相关阅读:
    快递标示
    git 操作命令系列
    在线js调试地址
    jQuery 的 validator 验证动态添加的信息
    mysql批量插入
    array_map 批量对数据执行某个自定义方法
    使用 header函数实现文件下载
    设置UTF-8 编码
    常用短信接口平台
    async: false 实现AJAX同步请求 ( $.ajax同步/异步(async:false/true) )
  • 原文地址:https://www.cnblogs.com/zhenghuiwen/p/12504885.html
Copyright © 2011-2022 走看看