一、read()方法
- 特点: 一次性读取整个文件,将文件内容放到一个字符串变量中。
- 劣势:如果文件非常大,尤其是大于内存时,无法使用read()方法
with open("./file_open.text", "r") as fp:
st = fp.read()
print(type(st))
print(st)
<class ‘str’>
this is the first
this is the second
this is the third
二、readline()方法
- 特点:readline()方法每次读取一行;返回的是一个字符串对象,保持当前行的内存
- 缺点:比readlines慢得多
with open("./file_open.text","r") as fp:
st = fp.readline()
print(type(st))
print(st)
<class ‘str’>
this is the first
三、readlines方法
- 特点:一次性读取整个文件,自动将文件内容分析成一个行的列表。
with open("./file_open.text", "r") as fp:
st_list = fp.readlines()
print(type(st_list))
print(st_list)
<class ‘list’>
[‘this is the first\n’, ‘this is the second\n’, ‘this is the third\n’]