【问题标题】:multiple search and replace in pythonpython中的多次搜索和替换
【发布时间】:2011-10-24 17:21:49
【问题描述】:

我需要在父文件夹中搜索所有 config.xml 文件 并在这些文件中替换另一个字符串。 (从this-is到where-as)

【问题讨论】:

  • 到目前为止您尝试过什么?什么不起作用,你在哪里卡住了?
  • 为什么要使用 Python?您可以使用 find 和 sed 从 shell 执行此操作。
  • 事先记录并尝试自己的一些想法是一个好主意,如果您无法处理,请提出问题,也许您尝试了一些代码/算法步骤。不是刻薄或任何东西,但从你的帖子来看,在我看来你没有尝试任何事情,只是希望别人解决你的问题。
  • 实际上我确实尝试过.. :)

标签: python replace


【解决方案1】:

您想看看 os.walk() 以递归方式遍历文件夹和子文件夹。

然后,您可以读取每一行 (for line in myfile: ...) 并进行替换 (line = line.replace(old, new)) 并将该行保存回临时文件 (tmp.write(line)),最后将临时文件复制到原始文件上。

【讨论】:

  • 谢谢。我给出的例子不起作用:(它什么也没做。
【解决方案2】:
import os
parent_folder_path = 'somepath/parent_folder'
for eachFile in os.listdir(parent_folder_path):
    if eachFile.endswith('.xml'):
       newfilePath = parent_folder_path+'/'+eachFile
       file = open(newfilePath, 'r')
       xml = file.read()
       file.close()
       xml = xml.replace('thing to replace', 'with content')
       file = open(newfilePath, 'w')
       file.write(str(xml))
       file.close()

希望这是您正在寻找的。​​p>

【讨论】:

  • 到目前为止我尝试过: import os parent_folder_path = 'c:/test' for eachFile in os.listdir(parent_folder_path): if eachFile.endswith('.xml'): newfilePath = parent_folder_path+'/' +eachFile file = open(newfilePath, 'r') xml = file.read() file.close() xml = xml.replace('Linux-ildev4', 'Linux09') file = open(newfilePath, 'w') file.write(str(xml)) file.close()
  • 所以不是替换了吗?或其他一些错误?如果它没有替换,请确保您要替换的文本在那里并且str.replace 也区分大小写。
  • 它不会替代任何东西。我确实确保文本的大小写正确......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-09
  • 2016-05-05
  • 2015-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多