簡體   English   中英

Python:在文本文件中查找字符串,如果找到,則在下一行寫一個字符串

[英]Python: Find a string in text file and if found write a string on immediate next line

我試圖編寫一個簡單的python代碼,在其中尋找文本文件中的字符串,一旦找到字符串,我想在txt文件的下一行中寫一些注釋。 我還想確保下一行中沒有注釋。 這是我到目前為止寫的。 但是,不是在下一行寫注釋,而是在不同的地方寫(看起來我對文件指針的當前位置未使用正確的語法)。 同樣,即使我在下一行上已有注釋,代碼的“其他”部分也永遠不會執行。

#!/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()

修改代碼以搜索兩個字符串

#!/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

請嘗試以下代碼。 請注意,它將為包含match的文件中的每一行打印"Pragma off comment already present on next line"

#!/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))

例子

文件包含以下文本

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 

運行該方法后,如下所示:

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

..和預期的一樣,即使您多次運行它,評論也不會超過一個:

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

編輯:回答您的其他問題 (在一行中搜索多個字符串並分別添加評論)

您可以使用字典將要添加的注釋映射到特定匹配項。 這會自動消除代碼中的冗余。

#!/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

最后一件事:代碼中的縮進不正確。 我不知道這是否是出於SO格式化的目的,但請參見此處以獲取更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM