我不太清楚在文件中替換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
,記錄下一行修改的時間。
備註:您的代碼示例建議您的文件中的數據是結構化的。閱讀這個結構並在其上工作,而不是在純文本文件上進行搜索和替換的方法肯定會更加節省。
你已經試過......?顯示您在解決問題時所付出的一些努力,錯誤或_code_。 –