0

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

1 Answer 1

3

Try the following code. Note that it prints "Pragma off comment already present on next line" for every line in the file that contains the match.

#!/comm/python/2.7.8/bin/python2.7
import re

comment = "// pragma coverage off"
match = "module"
content = []

with open ("bt5aura_bt5rf01_mixers.vams", "r+b") as file:
    for line in file:
        content.append(line)
        if match in line:
            nextLine = file.next().rstrip()
            if nextLine != comment:
                print "No pragma comment found on next line: %s" % nextLine
                content.append(comment + "\n")
            else:
                print "Pragma off comment already present on next line"
            content.append(nextLine + "\n")
    file.seek(0)
    file.truncate()
    file.write("".join(content))

Examples

A file contains the following text

no mod  
a module  
no mod again  
after the first run there should be a comment in the third row  
this should not change if you run it again 

After running the method, it looks like this:

no mod
a module
// pragma coverage off
no mod again
after the first run there should be a comment in the third row
this should not change if you run it again

..and as expected, there won't be more than one comment even if you run it several times:

no mod
a module
// pragma coverage off
no mod again
after the first run there should be a comment in the third row
this should not change if you run it again

Edit: Answer to your additional question (search for more than one String in one line and add a comment respectively)

You could use a dictionary to map the comment you want to add to the specific match. This automatically eliminates the redundancy in your code.

#!/comm/python/2.7.8/bin/python2.7
import re

comments = {"// pragma coverage off":"module ", "// pragma coverage on":"assign Check "}
content = []

# 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:
        amsModel = amsModel.rstrip('\n')
        with open (amsModel, "r+b") as file:
            for comment, match in comments.iteritems():
                print "*** Processing amsModel = {0} for: {1} ***".format(amsModel, key)
                for line in file:
                    content.append(line)
                        if value in line:
                        nextLine = file.next().rstrip()
                        if nextLine != comment:
                            print "No comment (\"{0}\") found on next line,\n nextline = {1}\n adding {0}".format(comment, nextLine, comment)
                            content.append(comment + "\n")
                        else:
                            print "comment (\"{0}\") already present on next line".format(comment)
                        content.append(nextLine + "\n")
                file.seek(0)
                file.truncate()
                file.write("".join(content1))
                file.close

One last thing: The indentation in your code was not correct. I don't know whether it was due to SO formatting purposes, but see here for more information.

Sign up to request clarification or add additional context in comments.

3 Comments

:Thanks a lot. That worked great. Now I'm trying to modify this code to find two strings and add comment if there is a match. I added break in for loop since I would like to implement this only on the first match. However modified code gives me a blank file as output. I'm assuming this is due to wrong file handling operations. Also I actually want to continue next string search from the point after first string is found. In that case, do I just set file pointer file.seek(1)? If first string is not found then I do not wish to continue to find second string.
Actually I figured it out. Also modified the code so that it takes a file as input which has list of filepaths in it. It opens all the files one by one and does the 'two string search' operation. Updated the original post with new code. Let me know if you have any more pointers. Thanks again for the help.
Glad I could help! I have updated my answer with an improved version of your two-string-search. If this answer solved your problem please mark it as accepted by clicking the check mark next to the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.