文件

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\n",b"bbb\n",b"ccc"] #加b = encoding 解码
    f.writelines(l)


with open(r"aaa","wb") as f:
    l = [bytes("小花花\n",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'))
posted @ 2020-03-17 10:53  迎着阳光  阅读(117)  评论(0编辑  收藏  举报