我正在尝试从另一个 python 文件替换/修改 python 文件中的一部分字符串。
我试图在其他 PY 中替换的行是:
a.setSystemFile('D:/test/f.xml')
我想用不同的 xml 路径替换此行的一部分,即 xml 路径字符串:
示例:
a.setSystemFile('C:/try/X.xml')
我的代码如下:
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')
但是,这会使文件为空并且只写入 C:/try/X.xml。有没有办法在保留原始内容的同时只替换上面示例中的 XML 路径字符串。
如有任何帮助,我们将不胜感激。谢谢。
最佳答案
如果该行不以该文本开头,您就忘记了做某事。
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)
另外,我可以建议只使用 sed为此?
关于python - 使用另一个 python 文件修改/替换 python 文件中的一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6199006/