Skip to main content
 首页 » 编程设计

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

2025年05月04日7傻小

我想在 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.