[英]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.