ファイル内の 0.5678 を置き換えるロジックについてはよくわかりません。そのため、関数を使用します。必要なものに変更するか、必要なものを詳細に説明します。行の最後の番号?浮動小数点数だけ?
試す:
import os
dirname = "14432826"
lines_distance= 4
def replace_whatever(line):
# Put your logic for replacing here
return line.replace("0.5678", "0")
for filename in filter(lambda x:x.endswith(".pz2") and not x.startswith("m_"), os.listdir(dirname)):
print filename
with open(os.path.join(dirname, filename), "r") as f_in, open(os.path.join(dirname,"m_%s" % filename), "w") as f_out:
replace_tasks = []
for line in f_in:
# search marker in line
if line.strip().startswith("translate"):
print "Found marker in", line,
replace_tasks.append(lines_distance)
# replace if necessary
if len(replace_tasks)>0 and replace_tasks[0] == 0:
del replace_tasks[0]
print "line to change is", line,
line_to_write = replace_whatever(line)
else:
line_to_write = line
# Write to output
f_out.write(line_to_write)
# decrease counters
for i, task in enumerate(replace_tasks):
replace_tasks[i] -= 1
コード内のコメントは理解に役立ちます。主な概念は、replace_tasks
次に変更する行がいつ来るかを記録するリストです。
備考: コード サンプルは、ファイル内のデータが構造化されていることを示唆しています。プレーン テキスト ファイルでの検索と置換のアプローチの代わりに、この構造を読み取って作業する方が間違いなく節約になります。