2016-10-27 5 views
0

文字列を見つけるとすぐに、テキストファイル内の文字列を探す単純なPythonコードを記述しようとしていますが、私は、txtファイルの次の行にコメントを書いています。コメントがまだ次の行に存在していないことを確認したい。ここまで私が書いたことがあります。しかし、次の行にコメントを書くのではなく、別の場所に書きます(ファイルポインタの現在の場所に正しい構文を使用していないように見えます)。また、次の行に既にコメントがある場合でも、コードの "else"部分は実行されません。Python:テキストファイル内の文字列を見つけ、すぐ次の行に文字列を書き込む

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

2つの文字列

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

答えて

2

次のコードを試してみてくださいを検索するためのコードを修正しました。 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 

は..and、数回実行しても複数のコメントはありませんS:

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 

編集:

は、あなたがしたいコメントをマッピングするために辞書を使用することができます(1行に複数の文字列を検索し、それぞれコメントを追加する)あなたの追加質問への回答特定のマッチに追加する。これにより、自動的にコードの冗長性が排除されます。

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

最後の1つ:コードのインデントが正しくありません。私はそれがSOのフォーマット目的によるものかどうかはわかりませんが、詳細はhereを参照してください。

+0

:ありがとうございます。それは素晴らしい仕事でした。今私は2つの文字列を検索し、一致がある場合はコメントを追加するこのコードを変更しようとしています。私は最初の試合でのみこれを実装したいので、forループでbreakを追加しました。しかし、修正されたコードは私に出力として空のファイルを与えます。私はこれが間違ったファイル処理操作のためだと仮定しています。また、実際には、最初の文字列が見つかった後の次の文字列検索を続けたいと思っています。その場合、ファイルポインタfile.seek(1)を設定するだけですか?最初の文字列が見つからない場合は、2番目の文字列を探し続けることは望ましくありません。 – sanforyou

+0

実際に私はそれを理解しました。また、コードを変更して、ファイルパスのリストを持つファイルを入力として受け取ります。すべてのファイルを1つずつ開き、「2文字列検索」操作を行います。元の投稿を新しいコードに更新しました。ポインタがあれば教えてください。助けてくれてありがとう。 – sanforyou

+0

うれしい私は助けることができました!あなたの2文字列検索の改良版で私の答えを更新しました。この回答があなたの問題を解決した場合は、回答の横にあるチェックマークをクリックして、それを合格とマークしてください。 – ncw

関連する問題