我使用for循环来读取文件,但我只想读取特定的行,比如第26行和第30行。是否有任何内置功能来实现这一点?
当前回答
其中一些很可爱,但可以做得更简单:
start = 0 # some starting index
end = 5000 # some ending index
filename = 'test.txt' # some file we want to use
with open(filename) as fh:
data = fin.readlines()[start:end]
print(data)
这将使用简单的列表切片,它加载整个文件,但大多数系统将适当地最小化内存使用,它比上面给出的大多数方法都快,并且适用于我的10G+数据文件。好运!
其他回答
文件对象有一个.readlines()方法,它将为您提供文件内容的列表,每个列表项一行。在此之后,您可以使用普通的列表切片技术。
http://docs.python.org/library/stdtypes.html#file.readlines
f = open(filename, 'r')
totalLines = len(f.readlines())
f.close()
f = open(filename, 'r')
lineno = 1
while lineno < totalLines:
line = f.readline()
if lineno == 26:
doLine26Commmand(line)
elif lineno == 30:
doLine30Commmand(line)
lineno += 1
f.close()
你可以用已经有人提到过的语法很简单地做到这一点,但这是迄今为止最简单的方法:
inputFile = open("lineNumbers.txt", "r")
lines = inputFile.readlines()
print (lines[0])
print (lines[2])
@OP,你可以使用枚举
for n,line in enumerate(open("file")):
if n+1 in [26,30]: # or n in [25,29]
print line.rstrip()
为了提供另一种解决方案:
import linecache
linecache.getline('Sample.txt', Number_of_Line)
我希望这是快速和简单的:)