read方法:
1. 不定长参数,表示读取文件中的所有数据
2. 指定数据长度,读取指定长度的数据
2.1 如果文件的操作模式是r模式,read(5) 表示这一次最多读取5个字符串长度的数据
2.2 如果文件的操作模式是rb模式,read(5) 表示这一次最多读取5个字节长度的数据
# ============================r 模式读取指定长度的数据 ===================
file = open("1.txt", "r", encoding="utf-8")
while True:
# 这里5表示最多读取5个字符串长度的数据
data = file.read(5)
if len(data) > 0:
print(data)
else:
print("数据读取完毕!")
break
# data = file.read(3)
# print(data)
file.close()
#我爱中国
数据读取完毕!
# # ============================rb 模式读取指定长度的数据 ===================
file = open("2.txt", "rb")
# 在utf-8编码格式化下,一个汉字占用3个字节,一个字母、数字、符号占用1个字节。
result = file.read(3)
print(result, type(result))
#b'hel' <class 'bytes'>
# 把字节数据解码成字符串
content = result.decode("utf-8")
print(content, type(content))
file.close()
#hel <class 'str'>
f = open('test.txt', 'r')
# 文件内容如果换行,底层有\n,会有字节占位,导致read书写参数读取出来的眼睛看到的个数和参数值不匹配
# read不写参数表示读取所有;
# print(f.read())
print(f.read(10))
f.close()
输出内容:
aaaaa
bbbb