4
\$\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?

Zuul
5067 silver badges20 bronze badges
asked Oct 9, 2012 at 7:53
\$\endgroup\$

1 Answer 1

4
\$\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)
answered Oct 9, 2012 at 8:38
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.