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'))
  • 相关阅读:
    IE安全级别没法定制
    将应用部署到Websphere的context root根/
    SqlServer插入慢的问题解决
    SqlServer中用@@IDENTITY取最新ID不准的问题
    分享我的戒烟经验
    Telnet发邮件过程
    .net垃圾回收和CLR 4.0对垃圾回收所做的改进之三
    Please pay more attention to the character set of your database
    翻旧贴: 什么是对象?
    C# Code in ASPX Page
  • 原文地址:https://www.cnblogs.com/zhangjinyi97/p/12509224.html
Copyright © 2011-2022 走看看