Shi Jie Tio
Shi Jie Tio

Reputation: 2529

How to use python code remove txt line before string?

I have Sample.txt file as below:

back
bold
yellow
green
country
code
bold
hello
yellow
country
code
bold
country

I wish to delete the first few line before country,so expected outcome is

country
code
bold
hello
yellow
country
code
bold
country

Anyone have ideas on this?

Upvotes: 0

Views: 35

Answers (2)

shriakhilc
shriakhilc

Reputation: 3000

You could get the list of lines in the file, use index to get the first occurrence of 'country' and then slice the list.

with open('Sample.txt') as inpfile:
    lines = list(map(str.strip, inpfile.readlines()))
    print(len(lines))
    print(lines[lines.index('country'):])

Or you could loop over the file and only start storing the lines after you encounter country (this would avoid loading everything into a list first):

with open('Sample.txt') as inpfile:
    is_storing = False
    lines = []
    for l in inpfile:
        if not is_storing and l.strip() == 'country':
            is_storing = True

        if is_storing:
            lines.append(l.strip())

    print(lines)

Upvotes: 0

Adam.Er8
Adam.Er8

Reputation: 13413

you can use list.index() to find out the position of country in the list, and then use slicing to get everything after it.

could you please try this, and let me know how it works for you?

content = []
with open('Sample.txt') as f:
    content = f.readlines()

content = content[content.index('country\n'):]

with open('Sample.txt', 'w+') as f:
    f.writelines(content)

Upvotes: 1

Related Questions