【发布时间】:2013-05-31 10:49:59
【问题描述】:
我总是在</IfModule> 模式之前添加我的新行。
我怎样才能用 Python 做到这一点。
仅供参考,我的文件不是使用 lxml/元素树的 XML/HTML。 IfModule 是我的.htaccess 文件的一部分
我的想法是反转文件并搜索模式,如果找到,就在它后面附加我的行。不太确定如何继续。
【问题讨论】:
标签: python
我总是在</IfModule> 模式之前添加我的新行。
我怎样才能用 Python 做到这一点。
仅供参考,我的文件不是使用 lxml/元素树的 XML/HTML。 IfModule 是我的.htaccess 文件的一部分
我的想法是反转文件并搜索模式,如果找到,就在它后面附加我的行。不太确定如何继续。
【问题讨论】:
标签: python
通读文件,当你找到要输出的那一行时,先输出一些东西,然后输出原来的那一行。
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,
【讨论】:
print line, 上的尾随 , 很重要 - 这不是错字;)
可以尝试将</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>"))
【讨论】: