77

我想在阅读文本文件时跳过前 17 行。

假设文件如下所示:

0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
good stuff

我只想要好东西。我正在做的事情要复杂得多,但这是我遇到麻烦的部分。

4

9 回答 9

148

使用切片,如下所示:

with open('yourfile.txt') as f:
    lines_after_17 = f.readlines()[17:]

如果文件太大而无法加载到内存中:

with open('yourfile.txt') as f:
    for _ in range(17):
        next(f)
    for line in f:
        # do stuff
于 2012-03-06T05:57:51.667 回答
40

使用itertools.islice,从索引 17 开始。它会自动跳过前 17 行。

import itertools
with open('file.txt') as f:
    for line in itertools.islice(f, 17, None):  # start=17, stop=None
        # process lines
于 2012-03-06T06:02:32.343 回答
3
for line in dropwhile(isBadLine, lines):
    # process as you see fit

完整演示:

from itertools import *

def isBadLine(line):
    return line=='0'

with open(...) as f:
    for line in dropwhile(isBadLine, f):
        # process as you see fit

优点:这很容易扩展到前缀行比“0”更复杂(但不相互依赖)的情况。

于 2012-05-06T23:08:10.877 回答
1

以下是前 2 个答案的 timeit 结果。请注意,“file.txt”是一个文本文件,其中包含 100,000 多行随机字符串,文件大小为 1MB+。

使用迭代工具:

import itertools
from timeit import timeit

timeit("""with open("file.txt", "r") as fo:
    for line in itertools.islice(fo, 90000, None):
        line.strip()""", number=100)

>>> 1.604976346003241

使用两个 for 循环:

from timeit import timeit

timeit("""with open("file.txt", "r") as fo:
    for i in range(90000):
        next(fo)
    for j in fo:
        j.strip()""", number=100)

>>> 2.427317383000627

显然 itertools 方法在处理大文件时更有效。

于 2018-12-27T09:37:44.380 回答
0

该解决方案帮助我跳过了linetostart变量指定的行数。如果您也想跟踪它们,您将获得索引 (int) 和行 (string)。在您的情况下,您将 linetostart 替换为 18,或将 18 分配给 linetostart 变量。

f = open("file.txt", 'r')
for i, line in enumerate(f, linetostart):
    #Your code
于 2016-01-19T19:25:41.267 回答
0

如果是桌子。

pd.read_table("path/to/file", sep="\t", index_col=0, skiprows=17)

于 2016-08-27T21:43:09.630 回答
-1

您可以使用 List-Comprehension 使其成为单线:

[fl.readline() for i in xrange(17)]

有关PEP 202Python 文档中的列表理解的更多信息。

于 2012-03-06T05:59:49.543 回答
-1

这是一种获取文件中两个行号之间的行的方法:

import sys

def file_line(name,start=1,end=sys.maxint):
    lc=0
    with open(s) as f:
        for line in f:
            lc+=1
            if lc>=start and lc<=end:
                yield line


s='/usr/share/dict/words'
l1=list(file_line(s,235880))
l2=list(file_line(s,1,10))
print l1
print l2

输出:

['Zyrian\n', 'Zyryan\n', 'zythem\n', 'Zythia\n', 'zythum\n', 'Zyzomys\n', 'Zyzzogeton\n']
['A\n', 'a\n', 'aa\n', 'aal\n', 'aalii\n', 'aam\n', 'Aani\n', 'aardvark\n', 'aardwolf\n', 'Aaron\n']

只需使用一个参数调用它即可从第 n 行 -> EOF 获取

于 2012-03-06T06:42:27.443 回答
-1

如果您不想一次将整个文件读入内存,可以使用一些技巧:

你可以前进到next(iterator)下一行:

with open("filename.txt") as f:
     next(f)
     next(f)
     next(f)
     for line in f:
         print(f)

当然,这有点难看,所以 itertools 有更好的方法:

from itertools import islice

with open("filename.txt") as f:
    # start at line 17 and never stop (None), until the end
    for line in islice(f, 17, None):
         print(f)
于 2018-04-14T20:45:32.607 回答