如何使这段代码的内存消耗少一点又简单?
How to make this code a bit less memory consuming yet simple?
到 return txt 文件中的特定行以进行进一步操作,而且此函数必须打开的文件非常大 ~ 500 行,因此创建一个列表然后打印特定行看起来很不错荒诞。你能给我一个替代方案吗?代码如下:
def returnline(filename, n):
ofile = open(filename, 'r')
filelist = ofile.readlines()
return filelist[n - 1].strip('\n')
如果你的文件不是几千行,我不会担心优化那一点,但是,你可以做的就是继续阅读文件,直到你到达你想要的行,然后停止阅读从那以后;这样,如果文件有 5000 行,而您想要第 10 行,则只需阅读 10 行。此外,您需要在打开并读取文件后将其关闭。
总而言之,是这样的:
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:
# (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)
...可以缩短为:
from itertools import islice
def line_of_file(fname, linenum):
with open(fname, 'r') as f:
return next(islice(f.xreadlines(),
linenum - 1,
linenum))
(在 Python 2.x 中,islice(xs, n, m)
类似于 xs[n:m]
除了 islice
适用于生成器;参见 https://docs.python.org/2/library/itertools.html#itertools.islice)
到 return txt 文件中的特定行以进行进一步操作,而且此函数必须打开的文件非常大 ~ 500 行,因此创建一个列表然后打印特定行看起来很不错荒诞。你能给我一个替代方案吗?代码如下:
def returnline(filename, n):
ofile = open(filename, 'r')
filelist = ofile.readlines()
return filelist[n - 1].strip('\n')
如果你的文件不是几千行,我不会担心优化那一点,但是,你可以做的就是继续阅读文件,直到你到达你想要的行,然后停止阅读从那以后;这样,如果文件有 5000 行,而您想要第 10 行,则只需阅读 10 行。此外,您需要在打开并读取文件后将其关闭。
总而言之,是这样的:
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:
# (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)
...可以缩短为:
from itertools import islice
def line_of_file(fname, linenum):
with open(fname, 'r') as f:
return next(islice(f.xreadlines(),
linenum - 1,
linenum))
(在 Python 2.x 中,islice(xs, n, m)
类似于 xs[n:m]
除了 islice
适用于生成器;参见 https://docs.python.org/2/library/itertools.html#itertools.islice)