对于以下内容:
def linecount(filename):
count = 0
for x in open(filename):
count += 1
return count
脚本如何“知道”每一行都是一个单独的元素? 对于"file"类型,这是按行分隔的方式吗?谢谢
请您参考如下方法:
因为当您遍历 file 对象时,它的行为就好像您正在遍历:
open(filename).readlines()
但不存储到内存(这对大文件有好处)。
Python 文档对此进行了更详细的解释,但这里是有趣的内容:
>>> f = open('foo.txt', 'r')
>>> f.readlines()
['This is the first line of the file.\n', 'Second line of the file\n']
另一种读取行的方法是遍历文件对象。这是内存效率高、速度快,并且代码更简单:
>>> for line in f:
print line,
This is the first line of the file.
Second line of the file
