-1

I am doing this as an assignment. So, I need to read a file and remove lines that start with a specific word.

fajl = input("File name:")
rec = input("Word:")
        
def delete_lines(fajl, rec):
    with open(fajl) as file:
        text = file.readlines()
        print(text)
        for word in text:
            words = word.split(' ')
            first_word = words[0]
            for first in word:
                if first[0] == rec:
                    text = text.pop(rec)
                    return text
                    print(text)
                return text

delete_lines(fajl, rec)

At the last for loop, I completely lost control of what I am doing. Firstly, I can't use pop. So, once I locate the word, I need to somehow delete lines that start with that word. Additionally, there is also one minor problem with my approach and that is that first_word gets me the first word but the , also if it is present.

Example text from a file(file.txt):

This is some text on one line.

The text is irrelevant.

This would be some specific stuff.

However, it is not.

This is just nonsense.

rec = input("Word:") --- This

Output:

The text is irrelevant.

However, it is not.

Matija
  • 69
  • 8

1 Answers1

1

You cannot modify an array while you are iterating over it. But you can iterate over a copy to modify the original one

fajl = input("File name:")
rec = input("Word:")
        
def delete_lines(fajl, rec):
    with open(fajl) as file:
        text = file.readlines()
        print(text)
        # let's iterate over a copy to modify
        # the original one without restrictions 
        for word in text[:]:
            # compare with lowercase to erase This and this
            if word.lower().startswith(rec.lower()):
                # Remove the line 
                text.remove(word)
    newtext="".join(text) # join all the text
    print(newtext) # to see the results in console
    # we should now save the file to see the results there
    with open(fajl,"w") as file:
        file.write(newtext)

print(delete_lines(fajl, rec))

Tested with your sample text. if you want to erase "this". The startswith method will wipe "this" or "this," alike. This will only delete the text and let any blank lines alone. if you don't want them you can also compare with "\n" and remove them

Julio González
  • 71
  • 1
  • 1
  • 5