Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Very simple I want to edit a virtual host files and replace the tags I made with some actual data:

import os, re
with open('virt_host', 'r+') as virtual
    file = virtual.read()
    file = re.sub('{{dir}}', '/home/richard', file)
    file = re.sub('{{user}}', 'richard', file)
    file = re.sub('{{domain_name}}', 'richard.com', file)

with open('new_virt', 'w+') as new_file
    new_file.write(file)
    new_file.close()

Is this the best way?

share|improve this question

1 Answer

import os, re

Here, make sure you put a colon after virtual

with open('virt_host', 'r+') as virtual:

Avoid using built-in Python keywords as variables (such as file here)

    f = virtual.read()

This part is explicit, which is a good thing. Depending on whether or not you have control over how your variables are defined, you could use string formatting to pass a dictionary containing your values into the read file, which would save a few function calls.

    f = re.sub('{{dir}}', '/home/richard', f)
    f = re.sub('{{user}}', 'richard', f)
    f = re.sub('{{domain_name}}', 'richard.com', f)

Same as above regarding the colon

with open('new_virt', 'w+') as new_file:
    new_file.write(f)

One of the main benefits of using a context manager (such as with) is that it handles things such as closing by itself. Therefore, you can remove the new_file.close() line.

Here is the full code with the adjustments noted. Hope it helps!

import os, re

with open('virt_host', 'r+') as virtual:
    f = virtual.read()
    f = re.sub('{{dir}}', '/home/richard', f)
    f = re.sub('{{user}}', 'richard', f)
    f = re.sub('{{domain_name}}', 'richard.com', f)

with open('new_virt', 'w+') as new_file:
    new_file.write(f)
share|improve this answer
wow thank you so much! – Jason Oct 9 '12 at 9:11
@Jason No prob man! – RocketDonkey Oct 9 '12 at 15:32

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.