繁体   English   中英

如何使用 Python 替换文件中的文本

[英]How to replace text in a file using Python

我想读取一个包含多行切换命令的大文件,然后启动一个包含相同文本命令列表的新文本文件,但只用所需的新文本替换几个字符或几行文本。

我还想有条件,这意味着如果存在一个指定的文本行,那么我希望将所需的文本替换为新文件中的位置。

我正在使用 Visual Studio 代码

所以你想要这样的东西:

output = ""
original_file  = ()

with open("file.txt", "r") as file:
    original_file = file.readlines()

for line in original_file:
    for word in line:
        if word == "#condition":
            output += "#new value"
        elif word == "#condition2":
            output += "#new value2"
        else:
            output += word  


with open("file.txt", "w") as file:
    file.write(output)

顺便说一下,我还没有运行代码,所以如果有任何错误,请告诉我。

所以这里有一个简短的例子:

with open("data.txt","r") as fin:
    with open("output2.txt","w") as fout:
        for aline in fin:
            new_data = aline
            if new_data.startswith("some data"):
                new_data = "replacement=string"
            elif "coffeebreak" in new_data:
                new_data = "coffee is schedualed at 10 on the 15th"
            fout.write(new_data+"\n") # You would want to end the line with a linebreak.

“data.txt”的内容:

some data we are logging
some data we are logging
we are having coffeebreak sometime soon
some data we are logging
something about the brown fox

Output 在我们的第二个文件“output2.txt”中:

replacement=string
replacement=string
coffee is schedualed at 10 on the 15th
replacement=string
something about the brown fox

使用with有很多好处,例如之后无需关闭文件。

希望这对你来说很好!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM