I'm trying to write a simple python code where I look for a string in a text file, as soon as I find a string, I want to write some comment in next line of a txt file. I also want to make sure that the comment is not already present in next line. Here is what I wrote so far. However instead of writing a comment on next line it writes at a different place (looks like I'm not using correct syntax for current location of a file pointer). Also "else" part of the code never executes even if I have a comment already present on next line.
#!/comm/python/2.7.8/bin/python2.7
import re
# Open a file
fo = open("bt5aura_bt5rf01_mixers.vams", "rw+")
print "Name of the file: ", fo.name
str1 = "// pragma coverage off"
# search for "module " to put "pragma coverge off" comment
for line in fo:
if 'module ' in line:
print line
nextLine=fo.next()
if nextLine.rstrip!=str1:
print "NO pragma comment found on next line:",nextLine.rstrip()
fo.seek(0,1)
line=fo.write(str1)
else:
print "Pragma off comment already present"
# Close opened file
fo.close()
Modified code to search two strings
#!/comm/python/2.7.8/bin/python2.7
import re
comment1 = "// pragma coverage off"
comment2 = "// pragma coverage on"
match1 = "module "
match2 = "assign Check "
# Open the file with ams filenames list.
with open('listofmodels.txt') as list_ams:
# Iterate over the lines, each line represents a file name.
for amsModel in list_ams:
content1 = []
content2 = []
amsModel = amsModel.rstrip('\n')
with open (amsModel, "r+b") as file:
print "***Processing amsModel=%s for pragma coverage off***" % amsModel
for line in file:
content1.append(line)
if match1 in line:
nextLine = file.next().rstrip()
if nextLine != comment1:
print "No pragma off comment found on next line,\n nextline=%s\n adding pragma off comment" % nextLine
content1.append(comment1 + "\n")
else:
print "Pragma off comment already present on next line"
content1.append(nextLine + "\n")
file.seek(0)
file.truncate()
file.write("".join(content1))
file.close
with open (amsModel, "r+b") as file:
print "***Processing amsModel=%s for pragma coverage on***" % amsModel
for line in file:
content2.append(line)
if match2 in line:
nextLine = file.next().rstrip()
if nextLine != comment2:
print "No pragma on comment found on next line,\n nextline=%s\n adding pragma on comment" % nextLine
content2.append(comment2 + "\n")
else:
print "Pragma on comment already present on next line"
content2.append(nextLine + "\n")
file.seek(0)
file.truncate()
file.write("".join(content2))
file.close
list_ams.close