2012-03-06 595 views
36

我想在读取文本文件时跳过前17行。在读取Python文件中的行时跳过第几行

比方说,文件看起来像:

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

我只是想的好东西。我所做的更复杂,但这是我遇到的问题。

+0

http://stackoverflow.com/questions/620367/python-how-to-jump-to-a-particular-line-in-a-huge-text-file 或 http://stackoverflow.com/questions/4796764/read-file-from-line-2-or-skip-header-row 等..? – 2012-03-06 05:57:57

回答

70

使用切片,像下面

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

如果文件过大在内存中加载:

with open('yourfile.txt') as f: 
    for _ in xrange(17): 
     next(f) 
    for line in f: 
     # do stuff 
+4

请记住,如果文件很大,这是一个坏主意,因为它将其全部读取到内存中 – 2012-03-06 05:58:44

+3

附加的解决方案是内存高效的 – 2012-03-06 07:56:48

+1

第二个解决方案是最好的,但为什么使用xrange?跳过 – 2015-11-24 13:37:39

0

您可以使用一个列表,理解,使之成为一个-liner:

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

更多关于list comprehensio n在PEP 202Python documentation

+1

没有太大意义将这些行存储在列表中,这些列表只会收集垃圾。 – wim 2012-03-06 06:04:53

+0

@wim:内存开销是微不足道的(可能无法避免,因为你需要对这些行进行O(n)处理,除非你跳到文件中的任意点);我只是不认为它很可读。 – ninjagecko 2012-05-06 23:13:35

+1

我同意@wim,如果你扔掉了结果,请使用循环。列表理解的重点在于你*表示存储列表;您可以轻松地在一行上安装for循环。 – David 2014-06-19 00:41:23

15
import itertools 
with open('file.txt') as f: 
    for line in itertools.islice(f, 17, None): # start=17, stop=None 
     # process lines 
0

这里是拿到两个号之间行文件的方法:

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

1
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”(但不相互依赖)更复杂的情况。

2

此解决方案帮助我跳过linetostart变量指定的行数。 如果你想跟踪这些,你可以得到index(int)和line(string)。 在你的情况下,你用18代替linetostart,或者把18代入linetostart变量。

f = open("file.txt", 'r') 
for i, line in enumerate(f, linetostart): 
    #Your code 
0

如果是表格。

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

相关问题