Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (45.3k points)
edited by

I'm trying to read a text from a text file, read lines, delete lines that contain specific string (in this case 'bad' and 'naughty'). The code I wrote goes like this:

infile = file('./oldfile.txt')

newopen = open('./newfile.txt', 'w')

for line in infile :

    if 'bad' in line:

        line = line.replace('.' , '')

    if 'naughty' in line:

        line = line.replace('.', '')

    else:

        newopen.write(line)

newopen.close()

I wrote like this but it doesn't work out.

One thing important is if the content of the text was like this:

good baby

bad boy

good boy

normal boy

I don't want the output to have empty lines. so not like:

good baby

good boy

normal boy

but like this:

good baby

good boy

normal boy

What should I edit from my code on the above?

1 Answer

0 votes
by (16.8k points)
edited by

You can make your code simpler and more readable like this:

bad_words = ['bad', 'naughty']

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)

using a Context Manager and any.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Jul 26, 2019 in Python by selena (1.6k points)
0 votes
1 answer
asked Jul 10, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
asked Jul 26, 2019 in Python by selena (1.6k points)

Browse Categories

...