How to loop through a list continuously while searching through

71 views Asked by At

Ok so I'm relatively new to python and this may be quite simple. However, I'm stumped. The code I have so far iterates through each line of a text file; reads each line; searches for a certain string within each line; if the string is found, the user is prompted to change a line x number of lines away, and then continues searching through the lines. What I want to be able to do is create a list of strings; have the program search each line for each string; if a string is found then same as previously described will happen; then once the new line has been created, the program will continue looking through each line for the strings and if it finds another line with one of the strings, it will overwrite a line x number of lines away. I've tried a 'for' loop to do this but haven't been successful so far. Ideas?

findArray1 = [find1,find2,find3]

#this is my initial attempt
with open(filename, 'r') as f:
        with open(filename+".BAK", 'w+') as newFile:
            for i,line in enumerate(f):
                if foundLine == 1:
                    foundLine += 1
                    newFile.write(line)
                elif (foundLine >= 2 and foundLine <=3):
                    number = float(input("Enter the overwrite string %swith: " %line))
                    splitLine = line.split('=')
                    newLine = "%s=%s\n" % (splitLine[0], number)
                    newFile.write(newLine)
                    foundLine += 1
                elif find4 in line:
                    foundLine = 1
                    newFile.write(line)
                elif find5 in line:
                    foundLine = 1
                    newFile.write(line)
                elif find6 in line:
                    foundLine = 1
                    newFile.write(line)    
                else:
                    newFile.write(line)

    os.remove(filename)

    os.rename(filename+".BAK", filename)

#idea for the loop instead of having all the elif and the else statements
else:
     for findLine in findArray1:
         for findLine in line:
             foundLine = 1
             newFile.write(line)
     newFile.write(line)
0

There are 0 answers