gpt4 book ai didi

python - 在 Python 中的特定行追加或删除文件中的某些文本

转载 作者:太空宇宙 更新时间:2023-11-04 06:25:28 25 4
gpt4 key购买 nike

我想在 python 脚本中编辑 Apache2 配置文件。我想向 ServerAlias 指令添加或删除域名,因此脚本需要编辑特定文件并搜索以“ServerAlias”开头的行,然后向该行附加或删除特定域名。

我不确定该怎么做,任何有关文档的提示都将不胜感激,我也在考虑使用子进程来使用一些 bash 工具,如 sed。

最佳答案

您可以在就地模式下使用 fileinput.input:

import fileinput

for line in fileinput.input("mifile", inplace=True):
if line.startswith("ServerAlias"):
line = doherewhatyouwant(line)
print line,

来自文档:

if the keyword argument inplace=True is passed to fileinput.input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently). This makes it possible to write a filter that rewrites its input file in place. If the backup parameter is given (typically as backup='.'), it specifies the extension for the backup file, and the backup file remains around; by default, the extension is '.bak' and it is deleted when the output file is closed. In-place filtering is disabled when standard input is read.

关于python - 在 Python 中的特定行追加或删除文件中的某些文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8686941/

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