好的,所以我对python来说比较新,这可能很简单。但是,我很难过。到目前为止,我所拥有的代码遍历文本文件的每一行;读取每一行;在每一行中搜索某个字符串;如果找到该字符串,则提示用户改变行x行数,然后继续搜索这些行。我想要做的是创建一个字符串列表;让程序搜索每个字符串的每一行;如果找到一个字符串,则会发生与之前描述相同的字符串;然后,一旦创建了新行,程序将继续查看字符串的每一行,如果它找到另一行与其中一个字符串,它将覆盖一行x行。我已经尝试了一个' for#39;循环做到这一点,但到目前为止还没有成功。想法?
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)