我无法解决如何打开文件以读取第7行的文字&并忽略该行的所有内容。如何从某一行开始阅读?
# Title #
<br />
2013-11-15
<br />
5
6
Random text
我没试过这里所描述的方法: python - Read file from and to specific lines of text
,但它搜索特定的匹配,包括上面那行文字。我需要相反的东西,包括从第7行开始的所有内容。
我无法解决如何打开文件以读取第7行的文字&并忽略该行的所有内容。如何从某一行开始阅读?
# Title #
<br />
2013-11-15
<br />
5
6
Random text
我没试过这里所描述的方法: python - Read file from and to specific lines of text
,但它搜索特定的匹配,包括上面那行文字。我需要相反的东西,包括从第7行开始的所有内容。
这将忽略前6行,然后从第7行打印所有行。
with open(file.txt, 'r') as f:
for i, line in enumerate(f.readlines(), 0):
if i >= 6:
print line
或@Paco建议:
with open(file.txt, 'r') as f:
for line in f.readlines()[6:]:
print line
你可以这样做:
首先创建一个演示文件:
# create a test file of 'Line X of Y' type
with open('/tmp/lines.txt', 'w') as fout:
start,stop=1,11
for i in range(start,stop):
fout.write('Line {} of {}\n'.format(i, stop-start))
现在与文件中的行,由工作-line:
with open('/tmp/lines.txt') as fin:
# skip first N lines:
N=7
garbage=[next(fin) for i in range(N)]
for line in fin:
# do what you are going to do...
您还可以使用itertools.islice:
import itertools
with open('/tmp/lines.txt') as fin:
for line in itertools.islice(fin,7,None):
# there you go with the rest of the file...
谢谢dawg。 – HexSFd
刚读6线,不跟他们做什么? –
我想读取从第7行开始的所有内容并忽略所有前面的行[1-6] – HexSFd
对。因此,打开文件,读取前六行并将它们扔掉,然后开始处理其他事情。 –