Bastian
Bastian

Reputation: 5865

Append or remove some text in a file at a specific line in Python

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

Answers (2)

joaquin
joaquin

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

Abhijit
Abhijit

Reputation: 63757

Couple of tools you would need for your trade

  1. str.startswith
  2. str.join or just + (string concatination)
  3. readline to read a file sequentially
  4. Offcourse opening and closing a file
  5. write a file

Upvotes: 0

Related Questions