Python没有覆盖文件

时间:2017-02-14 15:01:21

标签: python regex file

我试图通过替换该行中的某些关键字来覆盖特定文件的各个行。我已经研究了多个问题,大部分答案都显示了我已经实施的内容。 以下是代码:

datatype:'jsonp'

1 个答案:

答案 0 :(得分:1)

您可以将文件的文本保存为string,在完成编辑后将更改保存到stringswrite文本中。)

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)