Skip to content Skip to sidebar Skip to footer

Not Recognizing Loop Variable In Python

I am trying to delete 38 lines of text after coming across a certain phrase in a .txt file in Python, while still printing the rest of the text. The code I currently have is with o

Solution 1:

You would need to remove from the list, you cannot del the line, the easiest way is to write to a temp file and copy after if you want to modify the file, if you just want to print ignoring the 38 line replace write with print:

withopen('in.txt','r') as f,open('temp.txt','w') as temp:
    for line in f:
        if"phrase"in line:
            for i inrange(38):
                next(f) # skip 38 lineselse:
            temp.write(line)

Then use shutil to move the file:

import shutil

shutil.move("temp.txt","in.txt")

You can also use a NamedTemporaryFile:

from tempfile import NamedTemporaryFile

withopen('file.txt','r') as f, NamedTemporaryFile(dir=".",delete=False) as  temp:
    for line in f:
        if"phrase"in line:
            for i inrange(38):
                next(f)
        else:
            temp.write(line)

import shutil
shutil.move(temp.name,"file.txt")

The only potential problem I see is if the phrase is in one of the 38 ignored lines and you should also remove the next 38 lines from there.

To ignore until a second phrase, keep looping in the inner loop until you find the second phrase then break:

with open('in.txt','r') as f, NamedTemporaryFile(dir=".", delete=False) as temp:
    for line in f:
        if"phrase"in line:
            for _line in f:
                if"phrase2"in _line:
                    breakelse:
            temp.write(line)

Solution 2:

Instead of trying to delete lines from a file, write a new file based on the old one. The following uses __next__() to skip over lines yielded by the generator.

withopen('text_file.txt','r') as f, open('text_file_mod.txt', 'w') as w:
    for line in f:
        w.write(line)
        if"certain_phrase"in line:
            for num inrange(38): # skip 38 linesnext(f)

If you're doing this from the interactive interpreter, you can prevent it from spitting out returned values by saving the results of next(f) and w.write(line) to variables.

Solution 3:

del line actually deletes the variable line, meaning that when you try to do that a second time, it doesn't work, because line isn't defined anymore. You can loop over indices to find the line, break, then delete the next 38 lines:

with open('text_file.txt','r') as f:
lines = f.readlines()
for i in range(len(lines)):
    if"certain_phrase"inlines[i]:
        breakelse:
        print(line,end='')
for num in range(38):
    del lines[i]

Solution 4:

withopen('temp.txt','r') as fin:
    for line in fin:
        print(line,end="") #you want to print the phrase, right?if"certain_phrase"in line:
            for _ inrange(38):
                next(line)

Post a Comment for "Not Recognizing Loop Variable In Python"