1. read()
- 读取整个文件,将文件内容放到一个字符串变量中。read()直接读取字节到字符串中,包括了换行符。如果文件非常大,尤其是大于内存时,无法使用read()方法。
file = open('test.txt', 'r') # 创建的file,也是一个可迭代对象 for line in file: ...
try:
text = file.read() # 结果为str类型
print(type(text), text) # <class 'str'> 'text1\ntext2\n...'
except Exception as e:
print('read error', e)
file.close()
2. realine()
- readline()方法每次读取一行,返回的是一个字符串对象,保持当前行的内存。readline() 读取整行,包括行结束符,并作为字符串返回。读取比readlines慢。
file = open('test.txt', 'r')
try:
while True:
text_line = file.readline() # text_line = file.readline()[:-1] 去掉\n
if text_line:
print(type(text_line), text_line) # <class 'str'> 'text\n '
else:
break
except Exception as e:
print('read error', e)
finally:
file.close()
3. readlines()
- 一次性读取整个文件,自动将文件内容分析成一个行的列表。readlines()读取所有行然后把它们作为一个字符串列表返回。
file = open('test.txt', 'r')
try:
text_lines = file.readlines()
print(type(text_lines), text_lines) # <class 'list'> ['text\n', 'text\n', 'text\n',...]
for line in text_lines:
print(type(line), line) # <class 'str'> 'text\n'
finally:
file.close()