0

I'm trying to write a program to edit config files and the text is broken up into "paragraphs"

I want to search the file and find the "correct" paragraph - easy can do it with regex.

but from there I want to go down a few lines into say the middle of the paragraph/chunk of text and append to the end of the line, or copy the line do something to it, then write the line back.

example

define object {
       objectName    name_to_check
       useless_info  asdfasdf
       members       member1 member2 .... <- line I want to append to
}

I can't seem to find a way to do this online, any help would be greatly appreciated.

Maroun
  • 94,125
  • 30
  • 188
  • 241
Space Bear
  • 755
  • 1
  • 6
  • 18
  • You would have to read the file, find the place where you want to add the line - using regex and then modify the data and write it back to the file. – gaganso May 30 '16 at 14:41
  • You need to read about Python's StringIO. Lets see some coding.. – Merlin May 30 '16 at 15:12

2 Answers2

0

You could read the file into a string and then use string splitting. Let's say you have three lines:

config item one: True
config item two: "A"
config item three: 42

Using the answers from this question How to split a string into a list? and the "\n" delimiter to separate the lines, you get a list of 3 strings, each a single line from your file.

Search and change the line that you want to edit and then write all the lines into the file (overwrite the existing file). How to write a list of strings to a file is covered here: Writing a list to a file with Python

Community
  • 1
  • 1
Winandus
  • 1
  • 1
  • Yea thats what I'm thinking (working on now) read file into list, go through list till I get a match from a runtime generated regex, advance a few lines, edit, then overwrite file. I just feel its a bit inefficient. – Space Bear May 30 '16 at 14:53
  • 1
    The meat of your answer is behind a link. It's generally more helpful to include at least a line of code in your answer. – O. Jones May 30 '16 at 14:55
0

So I managed to get something working (just need to add a loop to write Ar to a file)

Ar = []
            file = open("path/To/File", "r")
            for line in file:
                    Ar.append(line)
            pattern = "(\s*hostgroup_name\s*"+host_group+"\s*)"
            p1 = re.compile(pattern)
            for i, line  in enumerate(Ar):
                    #print(line)
                    if p1.match(line):
                            #print(line)
                            Ar[i+2] = Ar[i+2][:-1]
                            Ar[i+2] += " " + host + "\n"
                            print(Ar[i+2])
                            break

host and host_group are variables I declared above.

thanks for the help people, but if theirs more efficient ways to do this I'm all ears.

Space Bear
  • 755
  • 1
  • 6
  • 18