问题描述
当使用for循环读取文件时,在某些情况下,我们只想读取特定的行,比如第26行和第30行,对于不同的情况,有3个内置特性可以实现这个目标。
When using a for loop to read a file, in some cases we only want to read specific lines, say line #26 and #30, there are 3 built-in features to achieve this goal for different cases.
For reading small files
对于小文件的快速解决办法:
Use fileobject.readlines()
or for line in fileobject
as a quick solution for small files.
f = open('filename')
lines=f.readlines()
print lines[25]
print lines[29]
or:
lines = [25, 29]
i = 0
f = open('filename')
for line in f:
if i in lines:
print i
i += 1
For reading many files, possible repeatedly
使用linecache
是一个更优雅的解决方案