python - 使用另一个 python 文件修改/替换 python 文件中的一行

我正在尝试从另一个 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为此?

https://stackoverflow.com/questions/6199006/

相关文章:

string - 如何测试 CComBSTR 是否为空

selenium - 如何在 selenium-webdriver 中处理视频?

ruby-on-rails - CSRF 在 Rails 中不起作用?

cookies - 如何在文本文件中生成cookie

api - ElementCollection 与 JPQL 方法上的 CriteriaBuilde

ruby-on-rails - rails : using helper methods from

wpf - 检测 CollectionView 何时刷新

arrays - Fortran90 数组将空白值读取为 null

macos - 在 MAC OS X 上的 MONO 中调用命令行

security - SaferCreateLevel SAFER_LEVELID_UNTRUSTE