可读、可写文件操作

t模式和字符编码有关
r+t:可读、可写
r+ 和 w+ 都是可读可写的,唯一区别就是r和w的区别,有无文件存在和是否会清空文件

w+t:可写、可读
with open('b.txt','w+t',encoding='utf-8') as f:
print(f.readable()) #True
print(f.writable()) # True

a+t:可追加写、可读


b模式
r+b
w+b
a+b

with open(r'C:UsersLENOVOPycharmProjectsuntitled2.txt',mode='rb') as f:
data=f.read()
data1 = f.readlines()
print(data)
print(data.decode('utf-8'))
print(data1) # 空列表,因为上面读过一边,光标已经在最后了(老是犯错)
print(data1.decode("utf-8")) #'list' object has no attribute 'decode'字符编码对象只能是字符串。

***

with open(r'C:UsersLENOVOPycharmProjectsuntitled2.txt',mode='rt',encoding='utf-8') as f:
data=f.read()
print(data)

with open(r'C:UsersLENOVOPycharmProjectsuntitled2.txt',mode='r+',encoding='utf-8') as f:
print(f.readline()) #***并不会在第三行直接加小红帽。数据在硬盘磁道上排列,如果有数据插入,所有数据都要移动,很显然,
# 操作系统不支持这样的操作,所以数据不会在光标位置直接插入数据。而是在末尾添加数据。
print(f.readline())
f.write('小红帽')



原文地址:https://www.cnblogs.com/Roc-Atlantis/p/9139870.html