1. read(): 一次性读取文件全部内容,适合小文件。举例如下:
with open('123.txt', 'r') as f:
print(f.read(), end='') # end=''用来关闭print默认添加换行符
2. read(size): 每次最多读取size个字节的内容,适合大文件。举例如下:
with open('123.txt', 'r') as f:
while True:
str = f.read(16) # 每次读取16字节
if not str:
break
print(str, end='')
3. readline(): 每次读取一行内容。举例如下:
with open('123.txt', 'r') as f:
while True:
str = f.readline() # 每次读取一行
if not str:
break
print(str, end='')
4. readlines(): 一次性读取所有内容并按行返回list,适合配置文件。举例如下:
with open('123.txt', 'r') as f:
for line in f.readlines():
print(line, end='')