aldegalan
aldegalan

Reputation: 502

Remove all lines containing a certain word

Having a string like this one:

AAAA AAAA
BBBB BBBB
CCCC CCCC
DDXD DDDD
EEEE EEEE
FXFF RRRR

How could I remove all the lines containing an "X"?

I know that I could do it from a txt file, but I would like to do it directly from the string...

The result must be:

AAAA AAAA
BBBB BBBB
CCCC CCCC
EEEE EEEE

I tried with:

with open('oldfile.txt') as oldfile, open('newfile.txt', 'w') as newfile:
    for line in oldfile:
        if not any(bad_word in line for bad_word in bad_words):
            newfile.write(line)

Upvotes: 1

Views: 50

Answers (2)

Buddy Bob
Buddy Bob

Reputation: 5889

You can easily accomplish this by using list comprehension. Iterate through your string (split by \n) and if a row is spotted without an X, then append it to a list.

stringRemoval = "AAAA AAAA\nBBBB BBBB\nCCCC CCCC\nDDXD DDDD\nEEEE EEEE\nFXFF RRRR"
cleanString = [line for line in stringRemoval.split('\n') if 'X' not in line]

Upvotes: 1

abcd
abcd

Reputation: 49

Try this:

with open("file.txt", "r") as f:
    lines = f.readlines()
with open("file.txt", "w") as f:
    for line in lines:
        if not "X" in line:
            f.write(line)

Upvotes: 1

Related Questions