내가 그 비트를 최적화에 대해 걱정하지 것이다, 그러나 당신이 할 수있는 것은 당신이 도달 할 때까지 파일을 읽는 유지 단순히 당신이 원하는 라인, 그리고 그곳에서 읽기를 중지하십시오; 그런 식으로, 파일이 말하자면 5000 줄이고, 10 번째 줄을 원하면 10 줄만 읽으면됩니다. 또한 파일을 열고 읽은 후에 파일을 닫아야합니다. 로 단축 할 수
from itertools import islice
def line_of_file(fname, linenum):
with open(fname, 'r') as f:
# (lazily) read all lines
lines = f.xreadlines()
# skip until the line we want
lines = islice(lines, linenum - 1, linenum)
# read the next line (the one we want)
return next(lines)
... : 모두 그래서
모두 이런 식으로 뭔가 :
def line_of_file(fname, linenum):
# this will ensure the file gets closed
# once the with block exits
with open(fname, 'r') as f:
# skip n - 1 lines
for _ in xrange(linenum - 1):
f.readline()
return f.readline().strip('\n')
는 또한, 발전기 (게으른 그룹, 가지) 더 나은 성능을 제공 할 수 있습니다 :
는
from itertools import islice
def line_of_file(fname, linenum):
with open(fname, 'r') as f:
return next(islice(f.xreadlines(),
linenum - 1,
linenum))
(파이썬 2.X에서 islice(xs, n, m)
0 제외 xs[n:m]
같다은 발전기에서 작동합니다. https://docs.python.org/2/library/itertools.html#itertools.islice 참조)