0

I have a text file called 'file.txt' that I want to loop through and remove any line that contains the word 'test'

so I opened the file in 'append' mode:

h = open('file.txt', 'a+')
for l in h:
    print('something') #to check if loop works
    if 'test' in l:
        h.write(l)

But nothing happens and if I try opening it in 'read' mode, i get an error io.UnsupportedOperation: not writeable On line 5

  • In your quesion you are saying your goal is to remove line that has keyword. In your code your writing same line if keyword present.. – Bhargav - Retarded Skills Nov 24 '22 at 15:24
  • @ThierryLathuille that question doesn't clearly cover writing back to the same file. That's better: https://stackoverflow.com/questions/4710067/how-to-delete-a-specific-line-in-a-file – mkrieger1 Nov 24 '22 at 15:24
  • @mkrieger1 I agree, but the way I understood what the OP means, the writing back to the file was just a failed attempt at doing what the introduction says, that is "remove any line that contains the word 'test'". – Thierry Lathuille Nov 24 '22 at 15:28
  • @Samuel, can you tell us if the duplicate answers your question? If not, please clarify why, and I'll reopen it. – Thierry Lathuille Nov 24 '22 at 15:29
  • The question does give me a way to do this by creating a new file but I what I really want to know is if there is a way to remove the line the same file? – Olamide Samuel Nov 24 '22 at 15:34
  • You can't remove a line from the middle of a file. You need to create the new, updated data and write the whole file again at once. – Thierry Lathuille Nov 24 '22 at 15:55

0 Answers0