文字列を見つけるとすぐに、テキストファイル内の文字列を探す単純な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つの文字列を検索し、一致がある場合はコメントを追加するこのコードを変更しようとしています。私は最初の試合でのみこれを実装したいので、forループでbreakを追加しました。しかし、修正されたコードは私に出力として空のファイルを与えます。私はこれが間違ったファイル処理操作のためだと仮定しています。また、実際には、最初の文字列が見つかった後の次の文字列検索を続けたいと思っています。その場合、ファイルポインタfile.seek(1)を設定するだけですか?最初の文字列が見つからない場合は、2番目の文字列を探し続けることは望ましくありません。 – sanforyou
実際に私はそれを理解しました。また、コードを変更して、ファイルパスのリストを持つファイルを入力として受け取ります。すべてのファイルを1つずつ開き、「2文字列検索」操作を行います。元の投稿を新しいコードに更新しました。ポインタがあれば教えてください。助けてくれてありがとう。 – sanforyou
うれしい私は助けることができました!あなたの2文字列検索の改良版で私の答えを更新しました。この回答があなたの問題を解決した場合は、回答の横にあるチェックマークをクリックして、それを合格とマークしてください。 – ncw