J. Wu
J. Wu

Reputation: 15

How to read a text file and delete it and associated lines, if it contains a certain string value?

For example, if I have a .txt file with basic telephone book information and I want to remove lines that contain something like "city=Seattle" from the said txt file. However, some names may contain a few extra lines or a note after the entry, which I want gone as well. Such as the following:

Name=John Doe, Address= 25 Main St, City=Denver,Phone= 1-310-999-9999

Note: John has a dog

Name=Jane Doe, Address= 12 Richard Rd, City=Seattle, Phone= 1-310-999-9999

Note: Jane is allergic to nuts

Name=Michael Smith, Address= 25 California BLVD, City=Los Angeles, Phone= 1-310-999-9999

After the script.py runs (and removing listings from seattle)

Name=John Doe, Address= 25 California BLVD, City=Denver, Phone= 1-310-999-9999

Note: John has a dog

Name=Michael Smith, Address= 25 California BLVD, City=Los Angeles, Phone= 1-310-999-9999*

This is what I have, but I don't know how to make it to deal with some names that may have note or log entries I want deleted

#read in my text file
file = open("phonebook.txt","r")
allLines = file.readlines()
file.close()
#rewrite my text file now
file = open("phonebook.txt","w")

#rewrite allLines into my text file but skip lines that contain seattle
for line in allLines:
  if "seattle" not in line:
    file.write(line)

Upvotes: 1

Views: 89

Answers (1)

Austin
Austin

Reputation: 26039

Traverse through alternate lines and write current and next line if current line does not contain "city=seattle".

#read in my text file
file = open("phonebook.txt","r")
allLines = file.readlines()
file.close()

allLines = list(filter(None, allLines))

#rewrite my text file now
file = open("phonebook.txt","w")

#rewrite allLines into my text file but skip lines that contain seattle
for x in range(0, len(allLines), 2):
  if "city=seattle" not in allLines[x].casefold():
    file.write(allLines[x])
    try:
        file.write(allLines[x+1])
    except IndexError:
        print('end')
file.close()

Upvotes: 1

Related Questions