Reputation: 5865
I want to edit an Apache2 config file within a python script. I want to add or remove a domain name to the ServerAlias directive so the script needs to edit a specific file and search for a line that starts with "ServerAlias" and append or remove a specific domain name to that line.
I'm not sure how to do it, any hint at documentation would be appreciated, I am also considering using a subprocess to use some bash tools like sed.
Upvotes: 2
Views: 2116
Reputation: 85663
you can use fileinput.input with inplace mode:
import fileinput
for line in fileinput.input("mifile", inplace=True):
if line.startswith("ServerAlias"):
line = doherewhatyouwant(line)
print line,
from docs:
if the keyword argument inplace=True is passed to fileinput.input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently). This makes it possible to write a filter that rewrites its input file in place. If the backup parameter is given (typically as backup='.'), it specifies the extension for the backup file, and the backup file remains around; by default, the extension is '.bak' and it is deleted when the output file is closed. In-place filtering is disabled when standard input is read.
Upvotes: 1
Reputation: 63757
Couple of tools you would need for your trade
+
(string concatination)Upvotes: 0