HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonMinor

How to improve method of opening file in python then writing to another?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
filemethodwritingimprovepythonthenhowanotheropening

Problem

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?

Solution

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)

Code Snippets

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)

Context

StackExchange Code Review Q#16341, answer score: 3

Revisions (0)

No revisions yet.