3

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.

1 Answer 1

2

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?

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks the above approach works. I would also consider using the SED , thanks for the info.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.