Python不覆盖文件

标签 python regex 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()

最佳答案

您可以将文件的文本保存到字符串,保存对该字符串的更改,并在完成后写入文本编辑:)

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/

相关文章:

php - 创建 PHP DOM xml 文件并创建保存文件链接/提示,而无需在 header 已发送时将文件写入服务器

python - 尝试理解 .strip

python - 如何使用 Python 读写 CSV 文件?

python - 索引范围对象时是否使用迭代协议(protocol)?

java - 扫描仪文件验证

Java:数据文件的相对路径

python - 是否可以在不创建本地端口的情况下在 Ruby 或 Python 中创建 SSH 隧道?

python - 在 numba 函数中创建一个新的列表/数组

regex - 当一个模式是 bash/awk 中的变量时如何在两种模式之间取线(动态正则表达式)

c - 在 C 中,如何获取捕获组 RegEx?