0

I want to replace a line in my file with new line(actually I have to insert some content in the line). The line actually contains AC_CONFIG_FILES([]) I have to replace this line with a new line by adding some makefile arguments based on some list. Then I constructed a new string and did replacement in the file. Is there any efficient way of doing this?

# 'subdirs' is the list which contains makefile arguments
rstring = "AC_CONFIG_FILES([Makefile"
for t in subdirs:
    rstring = rstring+' src/'+t+'/Makefile'
rstring += '])'
print rstring
# 'fname' is the file in which replacement have to be done
#  i is used for indexing in 'insert' function
# 'rline' is the modified line
fname = 'configure.ac'
i = 0
with open(fname,'r') as f:
      modlines=[]
      for line in f.readlines():
          if 'AC_CONFIG_FILES' in line:
                  modlines.insert(i,rstring+'\n')
                  i = i+1
                  continue
          modlines.insert(i,line)
          i = i+1
with open(fname,'w') as out:
      for i in range(len(modlines)):
          out.write(modlines[i])
Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260
Siva Krishna Aleti
  • 593
  • 1
  • 9
  • 23
  • Side note: your code formatting could usefully be improved: I suggest that you read and apply PEP 8. Furthermore, be careful not to write in Python like you would write in C: Python code is simpler than the code in this question; for instance, you often don't need indexes (see Johannes Charra's answer). – Eric O. Lebigot Sep 17 '13 at 07:56

1 Answers1

4

You could do this without loop/counter variables

modlines = []
with open(fname) as f:
    for line in f:
        if 'AC_CONFIG_FILES' in line:
            modlines.append(rstring + '\n')
        else:
            modlines.append(line)

with open(fname, 'w') as out:
    for line in modlines:
        out.write(line)
Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260
Johannes Charra
  • 29,455
  • 6
  • 42
  • 51