python中read、readline、readlines之间的区别

读写文件是最常见的IO操作。Python内置了读写文件的函数,用法和C是兼容的。读写文件前,我们先必须了解一下,在磁盘上读写文件的功能都是由操作系统提供的,现代操作系统不允许普通的程序直接操作磁盘,所以,读写文件就是请求操作系统打开一个文件对象(通常称为文件描述符),然后,通过操作系统提供的接口从这个文件对象中读取数据(读文件),或者把数据写入这个文件对象(写文件)。文件使用完毕后必须关闭,因为文件对象会占用操作系统的资源,并且操作系统同一时间能打开的文件数量也是有限的:

1、.read() 每次读取整个文件,它通常用于将文件内容放到一个字符串变量中。然而 .read() 生成文件内容最直接的字符串表示,但对于连续的面向行的处理,它却是不必要的,并且如果文件大于可用内存,则不可能实现这种处理。

file = open("./txt","r")
lines = file.read()
print(lines)
file.close()

执行结果:
I am chinese
I am chinese
I am chinese
I am chinese
Hello world

2、readlines:方法读取整个文件所有行,保存在一个列表(list)变量中,每行作为一个元素,但读取大文件会比较占内存。

file = open("./txt","r")
lines = file.readlines()
for i in lines:
	print(i)
print(lines)
file.close()

执行结果:
I am chinese

I am chinese

I am chinese

I am chinese

Hello world
['I am chinese
', 'I am chinese
', 'I am chinese
', 'I am chinese
', 'Hello world
']

3、readline:该方法每次读出一行内容,所以,读取时占用内存小,比较适合大文件,该方法返回一个字符串对象。

file = open("./txt","r")
lines = file.readline()
while lines:
	print(lines)
	lines = file.readline()
file.close()

执行结果:
I am chinese

I am chinese

I am chinese

I am chinese

Hello world

file = open( 'txt')        

for line in file.readlines():                    

print   line.readline() 和 .readlines()之间的差异是后者一次读取整个文件,象 .read()一样。.readlines()自动将文件内容分析成一个行的列表,该列表可以由 Python 的 for... in ... 结构进行处理。另一方面,.readline()每次只读取一行,通常比 .readlines()慢得多。仅当没有足够内存可以一次读取整个文件时,才应该使用.readline()。 

在你说话之前,先听;在你回应之前,先想;在你消费之前,先挣;在你退出之前,先试
原文地址:https://www.cnblogs.com/sunweigogogo/p/7511338.html