[英]Python not over-writing file
I am trying to overwrite individual lines of a particular file by replacing certain keywords within the line.我试图通过替换行中的某些关键字来覆盖特定文件的各个行。 I have already looked into multiple questions and most of the answers were showing what I have already implemented.
我已经研究了多个问题,大多数答案都显示了我已经实施的内容。 Following is the code:
以下是代码:
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()
You could save the text of the file to a string
, save the changes to that strings
and write
the text once you are finished editing :)你可以在文件的文本保存到一个
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
and just do the following right after that:然后立即执行以下操作:
with open(fileLocation, 'w') as openFile:
openFile.write(finalText)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.