高效文件读取 - python

来源:互联网 发布:java中this 编辑:程序博客网 时间:2024/05/24 04:57

特征解析

文件读取或写入时是被进程锁定的,所以我们应该尽早的file.close()

一般方法

f = open('FILENAME', 'r')longest = 0allLines = [x.strip() for x in f.readlines()]f.close()for line in allLines:    linelen = len(line)    if not linelen:        break;    if linelen > longest:        longest = linelenreturn longest

很容易发现,这一种方法是内存不友好的方法。

生成器方法

生成器的括号用()表示,所以我们还能把max函数套接上去:

longest = max(line(x.stip()) for x in f)f.close()return longeset

Pythoniccc!

return max(line(x.stip()) for x in open('FILENAME'))
1 0