Modify/replace a line in a python file using another python file
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.
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?
精彩评论