2

I always do append my new lines just before the pattern </IfModule>. How can i accomplish this with Python.

Just FYI, my file is not an XML/HTML to use lxml/element tree. IfModule is a part of my .htaccess file

My idea is to reverse the file and search for the pattern , if found append my line just after it. Not so sure how to proceed with.

millimoose
  • 39,073
  • 9
  • 82
  • 134
Sathy
  • 303
  • 2
  • 8
  • 18

2 Answers2

3

Read through the file, and when you find the line you're supposed to output before output something first, then output the original line.

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)

Updating the file inplace:

import fileinput

for line in fileinput.input('.htaccess', inplace=True):
    if line.strip() == '</IfModule>':
        print 'some stuff before the line'
    print line,
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
  • Thats simply superb.. BTW rather using two files, can we achieve it with a single file. Is that possible? – Sathy May 31 '13 at 11:00
  • @Sathy Yep. Updated to show how to update the file inplace (note the trailing `,` on `print line,` is important - it's not a typo ;) – Jon Clements May 31 '13 at 11:02
  • Since I'm new to this Site, I'm still earning my reputation. Please bear me for not giving you +1 ;) You are Awesome.. – Sathy May 31 '13 at 11:08
  • @Sathy no worries - glad it helped. Welcome to SO! – Jon Clements May 31 '13 at 11:10
  • @JonClements: Is it not fileinput.input('.htaccess', inplace=True)? – rajpy May 31 '13 at 11:20
  • @Sathy Just for the record, ``fileinput.input`` with ``inplace=True`` still uses two files (it will create ``.htaccess.bak`` behind the scenes). – lqc May 31 '13 at 11:48
  • Thanks Iqc, i also learnt that from [link](http://stackoverflow.com/questions/39086/search-and-replace-a-line-in-a-file-in-python) – Sathy May 31 '13 at 12:13
  • What to be done on this ? `Traceback (most recent call last): File "vanities.py", line 76, in make_changes() File "vanities.py", line 66, in make_changes for each_line in fileinput(short_conf,inplace=True): TypeError: 'module' object is not callable` I tried with using **from fileinput import fileinput**, i got `ImportError: cannot import name fileinput`. Please help – Sathy May 31 '13 at 12:37
  • @Sathy the code has already been corrected. rajpy was kind enough to point out a typo. The code now uses `for line in fileinput.input(...)` and just use `import fileinput` not `from fileinput import fileinput` – Jon Clements May 31 '13 at 12:40
  • +1, very nice, thanks! – Ida Jun 28 '13 at 12:51
1

Could try replacing </IfModule> with \n</IfModule>

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