【问题标题】:Python: How to add a line just before my matched pattern [duplicate]Python:如何在我匹配的模式之前添加一行[重复]
【发布时间】:2013-05-31 10:49:59
【问题描述】:

我总是在</IfModule> 模式之前添加我的新行。 我怎样才能用 Python 做到这一点。

仅供参考,我的文件不是使用 lxml/元素树的 XML/HTML。 IfModule 是我的.htaccess 文件的一部分

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

【问题讨论】:

    标签: python


    【解决方案1】:

    通读文件,当你找到要输出的那一行时,先输出一些东西,然后输出原来的那一行。

    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,
    

    【讨论】:

    • 这简直太棒了。顺便说一句,我们可以用一个文件来实现,而不是使用两个文件。这可能吗?
    • @Sathy 是的。更新以显示如何就地更新文件(注意 print line, 上的尾随 , 很重要 - 这不是错字;)
    • 由于我是这个网站的新手,我仍然在赢得我的声誉。请原谅我没有给你 +1 ;) 你太棒了..
    • @Sathy 不用担心 - 很高兴它有所帮助。欢迎来到 SO!
    • @JonClements:不是fileinput.input('.htaccess', inplace=True)吗?
    【解决方案2】:

    可以尝试将&lt;/IfModule&gt; 替换为\n&lt;/IfModule&gt;

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-05
      • 1970-01-01
      • 2021-04-17
      • 1970-01-01
      • 2016-08-24
      • 2019-01-03
      • 1970-01-01
      相关资源
      最近更新 更多