test.txt内容:
aaaa
bbbb
cccc
示例:
read
read()
with open('test.txt') as f:
# read()读取所有
a1 = f.read() # str
print(a1)
output:
aaaa
bbbb
cccc
read(size)
with open('test.txt') as f:
datas = []
# read([size])指定读取的字节数,包括\n
a1 = f.read(3) # str
while a1:
# 每次读取内容保存至datas
datas.append(a1)
a1 = f.read(3)
# 输出每次读取的内容
print(datas)
output:
[‘aaa’, ‘a\nb’, ‘bbb’, ‘\ncc’, ‘cc\n’]
readline
readline()
with open('test.txt') as f:
datas = []
# readline每次读取一行
a2 = f.readline() # str
while a2:
datas.append(a2)
a2 = f.readline()
print('readline():')
print(datas)
output:
[‘aaaa\n’, ‘bbbb\n’, ‘cccc\n’]
readline(size)
with open('test.txt') as f:
datas = []
# readline每次读取一行
# 指定读取字节数
a2 = f.readline(3) # str
while a2:
datas.append(a2)
a2 = f.readline(3)
print('readline(size):')
print(datas)
output:
[‘aaa’, ‘a\n’, ‘bbb’, ‘b\n’, ‘ccc’, ‘c\n’]
readlines
readlines()
with open('test.txt') as f:
# readlines一次读取所有行,返回列表
a3 = f.readlines() # list
print('readlines():')
print(a3)
output:
[‘aaaa\n’, ‘bbbb\n’, ‘cccc\n’]
readlines(size)???
with open('test.txt') as f:
a3 = f.readlines(1) # list
print('readlines(1):')
print(a3)
a3 = f.readlines(2) # list
print('readlines(2):')
print(a3)
a3 = f.readlines(3) # list
print('readlines(3):')
print(a3)
a3 = f.readlines(4) # list
print('readlines(4):')
print(a3)
output:
readlines(1):
[‘aaaa\n’]
readlines(2):
[‘bbbb\n’]
readlines(3):
[‘cccc\n’]
readlines(4):
[]