-1

How am I able to remove an entire string which has a certain word in it?

For example I have a file that contains:

Cheese is nice

Ham is also pretty tasty

This is fun

How can I input, the string with 'Ham' and it should be entirely deleted. So if I input Ham it removes the entire string.

Ham is also pretty tasty

dotmp3
  • 494
  • 4
  • 13
  • Should not be hard to combine from https://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list and https://docs.python.org/2/library/stdtypes.html#string-methods (function `find`). – starturtle Nov 07 '20 at 20:04
  • A good blog for reference to delete contents of a file based on certain conditions. https://thispointer.com/python-how-to-delete-specific-lines-in-a-file-in-a-memory-efficient-way/ – Prasad Deshmukh Nov 07 '20 at 20:22

1 Answers1

2

I think this is what you are asking for.

# Word that you are looking for
word = "Ham"

# Input file
input = open("file1.txt", "rt")
# Output file
output = open("file2.txt", "wt")

# Loops through each line in the input file
for line in input:
  # Checks if the word is in the line (Not case sensitive)
  if not (word.upper() in line.upper()):
    # Adds the line to the output file if the word is not found
    output.write(line)     

input.close()
output.close()
Dharman
  • 30,962
  • 25
  • 85
  • 135