Python:如何在匹配模式之前添加一行

时间:2013-05-31 10:49:59

标签: python

我总是在模式</IfModule>之前添加我的新行。 我怎样才能用Python实现这一目标。

仅供参考,我的文件不是使用lxml / element树的XML / HTML。 IfModule是我的.htaccess文件

的一部分

我的想法是反转文件并搜索模式,如果找到它后面附加我的行。不太确定如何继续。

2 个答案:

答案 0 :(得分:3)

通读文件,当您在输出内容之前找到要输出的行时,输出原始行。

with open('.htaccess') as fin, open('.htaccess-new', 'w') as fout:
    for line in fin:
        if line.strip() == '</IfModule>':
            fout.write('some stuff before the line\n')
        fout.write(line)

在原地更新文件:

import fileinput

for line in fileinput.input('.htaccess', inplace=True):
    if line.strip() == '</IfModule>':
        print 'some stuff before the line'
    print line,

答案 1 :(得分:1)

可以尝试将</IfModule>替换为\n</IfModule>

with open('.htaccess', 'r') as input, open('.htaccess-modified', 'w') as output:
    content = input.read()
    output.write(content.replace("</IfModule>","\n</IfModule>"))
相关问题