python判断文件读取结束_python中文件处理--判断文件读取结束方法

时间: 2023-07-29 admin 互联网

python判断文件读取结束_python中文件处理--判断文件读取结束方法

python判断文件读取结束_python中文件处理--判断文件读取结束方法

一、readline函数

按行遍历读取文件的方法,通过这个方法,readline() 每次只读取一行,通常比 .readlines() 慢得多。仅当没有足够内存可以一次读取整个文件时,才应该使用 .readline()

filename = raw_input('Enter your file name') #输入要遍历读取的文件路径及文件名

file = open(filename,'r')

done=0while notdone:

aLine=file.readline()if(aLine != ''):printaLine,else:

done= 1file.close()#关闭文件

二、readlines()

readlines() 自动将文件内容分析成一个行的列表,该列表可以由 Python 的 for ... in ... 结构进行处理

fh = open('c:\autoexec.bat')for line infh.readlines():print line