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)