[英]Python not over-writing file
我試圖通過替換行中的某些關鍵字來覆蓋特定文件的各個行。 我已經研究了多個問題,大多數答案都顯示了我已經實施的內容。 以下是代碼:
with open(fileLocation,"r+") as openFile:
for line in openFile:
if line.strip().startswith("objectName:"):
line = re.sub(initialName.replace(".qml",""),camelCaseName.replace(".qml",""),line)
print line
openFile.write(line)
openFile.close()
你可以在文件的文本保存到一個string
,將更改保存到該strings
和write
一旦你完成編輯的文本:)
finalText = "" # Here we will store the complete text
with open(fileLocation, "r") as openFile:
for line in openFile:
if line.strip().startswith("objectName:"):
line = ... # do whatever you want to do with the line.
finalText += line
然后立即執行以下操作:
with open(fileLocation, 'w') as openFile:
openFile.write(finalText)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.