Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify/replace a line in a python file using another python file

Tags:

python

I am trying to replace/modify a part of string in a python file from another python file.

The line I am trying to replace in other PY is :

a.setSystemFile('D:/test/f.xml')

I would like to replace the part of this line i.e. the xml path string with different xml path:

Example:

a.setSystemFile('C:/try/X.xml')

My code looks like:

with open('script.py') as f:  lines = f.read().splitlines()
with open('script.py', 'w') as f:

    for line in lines:
      if line.startswith('a.setSystemFile'):

        f.write(line.replace('D:/test/f.xml','C:/try/X.xml')

This however, renders the file empty and only writes C:/try/X.xml. Is there a way to preserve the original content at the same time replace just the XML path string like in above example.

Any help would be appreciated. Thanks.

like image 754
user741592 Avatar asked Jun 15 '26 17:06

user741592


1 Answers

You forgot to do something if the line doesn't start with that text.

for line in lines:
  if line.startswith('a.setSystemFile'):
    f.write(line.replace('D:/test/f.xml','C:/try/X.xml'))
  else:
    f.write(line)

Also, might I suggest just using sed for this?

like image 154
Ignacio Vazquez-Abrams Avatar answered Jun 18 '26 07:06

Ignacio Vazquez-Abrams