简体   繁体   中英

Python Skip one or more lines in a text file

I am trying to do something in Python2.7 and I would really appreciate any kind of help!!I have a txt file and I want to read each line and do some stuff with it (I haven't decided yet). Anyway, there are some lines that I don't want and I want to skip them and I don't know how to do it.I read about next() function, but I don't always know how many lines need to be skipped and I don't know exactly how to use next() eg.file.next() or next(iterator). To make myself clear, here is an example:

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

etc

and I am trying to do something like this:

if line=certain_condition:
    skip_this_line_and_the_next_one(s)_if_the_same_condition_applies_and_continue_to_the_next_line

Thank you in advance!!!

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

The continue simply tells python to ignore the rest of the body of the for loop and go back to the top. This way, any lines that pass some_condition are ignored.

In your case, you seem to want to ignore lines that have line_to_be_skipped . So, some_condition could look like this:

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

You can try using this

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

to skip specific lines:

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 is the list of lines that you wish to skip. You can probably use regex to avoid specific patterned lines that you want to skip (can be updated if you update your question).

I usually doing like this:

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

I would bet my money on this being a duplicate, but I couldn't find anything obvious with a 2 min search.

Anyway, the shortest way to do this is with a list comprehension.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM