2015-04-02 37 views
1

我想在Python2.7中做些什麼,我真的很感謝任何形式的幫助!!我有一個txt文件,我想閱讀每一行並做一些事情與它(我還沒有決定)。無論如何,有一些我不想要的,我想跳過它們,我不知道該怎麼做。我讀了next()函數,但我並不總是知道需要多少行跳過了,我不知道如何使用next()eg.file.next()或next(iterator)。 爲了讓自己清楚,這裏有一個例子:Python在文本文件中跳過一行或多行

mytxt: 
    line1 
    line2 
    line3 
    line_to_be_skipped_1 
    line_to_be_skipped_2 
    line6 
    line7 
    line8 
    line_to_be_skipped_3 
    line9 

etc 

,我試圖做這樣的事情:

if line=certain_condition: 
    skip_this_line_and_the_next_one(s)_if_the_same_condition_applies_and_continue_to_the_next_line 

預先感謝您!

回答

2
with open('/path/to/file') as infile: 
    for line in infile: 
     if some_condition(line): 
      continue 
     do_stuff(line) 

continue只是告訴蟒蛇忽略的體內循環的其餘部分並返回到頂部。這樣,任何通過some_condition的行都會被忽略。

就你而言,你似乎想忽略具有line_to_be_skipped的行。所以,some_condition看起來是這樣的:

def some_condition(line): 
    return "line_to_be_skipped" in line 
1

您可以嘗試使用此

with open('test.txt') as f: 
    for i in f: 
     if i != "AnyParticularStatementToBeSkipped": 
      # do any operations here 
1

跳過特定行:

x = [] 
f = open("filename") 
for line in f: 
    x.append(line) if line not in list_of_lines_to_skip 

list_of_lines_to_skip是想跳過線的列表。您可以使用正則表達式來避免您想要跳過的特定圖案線條(如果更新您的問題,可以更新)。

1

我平時做這樣的:

with open("mytxt", 'r') as f: 
    for line in f: 
     if "some pattern" in line: 
      continue 
     ''' 
     process the line you will not skip 
     ''' 
1

我敢打賭這個是一個重複我的錢,但我無法找到一個2分鐘的搜索任何明顯。

無論如何,最簡單的方法是使用列表理解。

with open("test.txt") as f: 
    res = [x for x in f if x.rstrip('\n') not in list_of_exclude_items] 
相關問題