mode
带'b'的表示二进制格式
1、rb
以二进制格式打开一个文件。当读取图片或进行文本传输时,需要转换为二进制格式。
# mode='rb'
# 'aaa.txt'内容为'我是一只猪猪侠'
f = open('aaa.txt', mode='rb')
content = f.read()
print(content, type(content))
f.close()
输出:
b'\xe6\x88\x91\xe6\x98\xaf\xe4\xb8\x80\xe5\x8f\xaa\xe7\x8c\xaa\xe7\x8c\xaa\xe4\xbe\xa0' <class 'bytes'>
2、wb
# mode='wb'
f = open('bbb.txt', mode='wb')
f.write('我是一只猪猪侠'.encode(encoding='utf-8'))
f.close()
'bbb.txt'文件:
我是一只猪猪侠
3、读写 r+
先读后写:
f = open('aaa.txt',mode='r+',enoding='utf-8')
# 打印aaa.txt的内容
print(f.read())
# 在aaa.txt的末尾写入"猪猪侠"
f.write('猪猪侠')
# 由于读写只支持读完再写,故没有输出
print(f.read())
f.close()
先写后读:
f=open('aaa.txt',mode='r+',encoding='utf-8')
# 先写:假设'aaa.txt'的内容为'python','aa'直接覆盖'py'
f.write('aa')
# 'aathon'
print(f.read())
f.close()
4、读写 二进制 r+b
f=open('aaa.txt',mode='r+b')
print(f.read())
f.write('aaa'.enode('utf-8'))
f.close()
5、写读
f=open('aaa.txt',mode='w+',encoding='utf-8')
# 清空写入
f.write('aaa')
# 无输出,因为光标默认移到了最后
print(f.read())
# 光标移到最开头:输出'aaa'
f.seek(0)
print(f.read())
f.close()
6、选择性读写
f=open('aaa.txt',mode='r+',encoding='utf-8')
# 获取光标位置 0
print(f.tell())
# 光标移至字节为3的地方,英文一个字符对应一个字节,中文一个字符对应三个字节
f.seek(3)
# 位置按字节定义 3
print(f.tell())
# 'aaa.txt'内容为'python' hon
print(f.read(3))
# 'aaa.txt'内容为'我是一只猪猪侠' '是一只'
print(f.read(3))
7、截取文件固定长度字符串
# 'aaa.txt'内容为'python'
f=open('aaa.txt',mode='r',encoding='utf-8')
# 'aaa.txt'保留前四个字符,即'pyth'
f.truncate(4)
f.close()