gpt4 book ai didi

python - 在 Python 中删除多行

转载 作者:太空宇宙 更新时间:2023-11-03 13:39:11 25 4
gpt4 key购买 nike

我有一个看起来像这样的文件:

<VirtualHost *:80>
ServerName Url1
DocumentRoot Url1Dir
</VirtualHost>

<VirtualHost *:80>
ServerName Url2
DocumentRoot Url2Dir
</VirtualHost>

<VirtualHost *:80>
ServerName REMOVE
</VirtualHost>

<VirtualHost *:80>
ServerName Url3
DocumentRoot Url3Dir
</VirtualHost>

我想删除这段代码的地方(它不会改变):

<VirtualHost *:80>
ServerName REMOVE
</VirtualHost>

我试图通过使用下面的代码找到整段代码,但它似乎不起作用。

with open("out.txt", "wt") as fout:
with open("in.txt", "rt") as fin:
for line in fin:
fout.write(line.replace("<VirtualHost *:80>\n ServerName REMOVE\n</VirtualHost>\n", ""))

最佳答案

最快的方法是将整个文件读入一个字符串,执行替换,然后将字符串写入您需要的文件。例如:

#!/usr/bin/python

with open('in.txt', 'r') as f:
text = f.read()

text = text.replace("<VirtualHost *:80>\n ServerName REMOVE\n</VirtualHost>\n\n", '')

with open('out.txt', 'w') as f:
f.write(text)

关于python - 在 Python 中删除多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34559800/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com