【问题标题】:How to start reading from certain line?如何从某行开始阅读?
【发布时间】:2013-11-16 02:43:42
【问题描述】:

我无法解决如何从第 7 行打开文件进行读写并忽略该行以上的所有内容。

# Title #
<br />
2013-11-15
<br />
5
6
Random text

我确实尝试了这里描述的方法: python - Read file from and to specific lines of text

但它会搜索特定匹配并包含该行上方的文本。我需要反过来,包括从第 7 行开始的所有内容。

【问题讨论】:

  • 只读了 6 行,什么都不做?
  • 我想阅读从第 7 行开始的所有内容并忽略之前的所有行 [1-6]
  • 对。所以打开文件,阅读前六行并将它们扔掉,然后开始你打算对其余部分做的任何事情。
  • 我认为你误解了 Mark Reed。你是什​​么意思“忽略”?我猜你想在阅读第 7 行后做一些事情。所以你只能阅读然后忽略第 1-6 行,最后阅读第 7 行并做一些事情。

标签: python


【解决方案1】:

这将忽略前 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

【讨论】:

  • 您不必将所有行读入带有readlines 的列表中。
  • 提示:itertools.islice
  • 没有理由将整个文件读入内存。这太不像Python了!
【解决方案2】:

你可以这样做:

首先创建一个演示文件:

# 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))

现在逐行处理文件:

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...  

【讨论】:

    猜你喜欢
    • 2014-09-20
    • 1970-01-01
    • 2017-03-14
    • 1970-01-01
    • 2011-02-26
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    相关资源
    最近更新 更多