3
\$\begingroup\$

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?

\$\endgroup\$

1 Answer 1

3
\$\begingroup\$
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)
\$\endgroup\$
1
  • \$\begingroup\$ @Jason No prob man! \$\endgroup\$ Commented Oct 9, 2012 at 15:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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