2012-03-06 279 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)

相關問題