A Bo
A Bo

Reputation: 45

Find the first instance of a variable in a .txt file and delete the line it is in

I have created a text file that holds different names, followed by a number in the format:

Name 1, 10
Name 2, 5
Name 3, 5
Name 2, 7
Name 2, 6
Name 4, 8
ect.

I want to find the line that the variable 'Name 2' first appears on - so line 2, and then delete that line. Is that possible?

Upvotes: 0

Views: 84

Answers (1)

falsetru
falsetru

Reputation: 369324

def skip_line_with(it, name):
    # Yield lines until find the line with `name`
    for line in it:
        if line.startswith(name):
            break  # Do not yield the line => skip the line
        yield line

    # Yield lines after the line
    for line in it:
        yield line

with open('a.txt') as fin, open('b.txt', 'w') as fout:
    fout.writelines(skip_line_with(fin, 'Name 2,'))

New file b.txt without unwanted line will be created.


UPDATE If you want to replace the file in-place (assuming file is not huge):

def skip_line_with(it, name):
    for line in it:
        if line.startswith(name):
            break
        yield line
    for line in it:
        yield line

with open('a.txt', 'r+') as f:
    replaced = list(skip_line_with(f, 'Name 2,'))
    f.seek(0)
    f.writelines(replaced)
    f.truncate()

Upvotes: 1

Related Questions