我试图通过替换行中的某些关键字来覆盖特定文件的各个行。我已经研究了多个问题,大多数答案都显示了我已经实现的内容。 代码如下:
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()
最佳答案
您可以将文件的文本保存到字符串
,保存对该字符串
的更改,并在完成后写入
文本编辑:)
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)
关于Python不覆盖文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42229426/