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


一、readline函数

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

filename = raw_input('Enter your file name') #输入要遍历读取的文件路径及文件名
file = open(filename,'r')
done = 0
while not done:
aLine = file.readline()
if(aLine != ''):
print aLine,
else:
done = 1
file.close() #关闭文件

二、readlines()

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

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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM