【问题标题】:Searching a folder structure and modifying XML files using Python使用 Python 搜索文件夹结构和修改 XML 文件
【发布时间】:2017-08-14 08:55:42
【问题描述】:

我正在尝试创建一个 python 脚本,它将遍历文件夹结构,查找名为“bravo”的文件夹,并修改其中包含的 xml 文件。

在xml文件中,我想修改一个标签的'location'属性,叫做'file'。如:

<file location="e:\one\two"/>

我只需要将文件路径的驱动器号从“e”更改为“f”。这样它就会变成:

<file location="f:\one\two"/>

不过……

这些 xml 文件的名称是唯一的,因此我无法搜索确切的 xml 文件名。相反,我正在搜索 xml 文件类型。

此外,我的文件夹结构中还有其他 xml 文件,没有“文件”标签引用,我希望忽略这些文件。

唯一不变的是,我要修改的 xml 文件都存储在名为“bravo”的文件夹中。

我还希望创建一个日志文件,列出所有已成功更新的 xml 文件及其文件路径(最好是那些失败的)。

使用本网站上类似问题的答案,我拼凑了以下脚本。

在当前状态下,脚本会尝试修改它找到的每个 xml 文件。我无法成功添加仅搜索名为“bravo”的文件夹的代码。

当脚本修改不在“bravo”文件夹中的 xml 文件时,它会出错,因为这些文件不包含“文件”标签。

请有人帮我更正我的脚本(或创建一个新脚本)。

这里是一个文件夹结构的例子……

My folder structure

到目前为止,我的脚本...

from xml.dom import minidom
   import os

   # enter the directory where to start search for xml files...

   for root, dirs, files in os.walk("c:/temp"):
       for file in files:
           #search for xml files...
           if file.endswith(".xml"):
               xml_file = file

               xmldoc = minidom.parse(os.path.join(root, xml_file))

               # in the xml file look for tag called "file"...
               file_location = xmldoc.getElementsByTagName("file")
               # i don't understand the next line of code, but it's needed
               file_location = file_location[0]

               # 'location_string' is a variable for the 'location' path of the file tag in the xml document
               location_string = (file_location.attributes["location"].value)

               # the new drive letter is added to the location_string to create 'new_location'
               new_location = "f" + location_string[1:]

               # replace the 'location' value of the file tag with the new location...
               file_location.attributes["location"].value = new_location

               # write the change to the original file
               with open((os.path.join(root, xml_file)),'w') as f:
               f.write(xmldoc.toxml())
               print "%s has been updated!" % (os.path.join(root, xml_file))
               # add updated file name to log...
               log_file = open("filepath_update_log.txt", "a")
               log_file.write("%s\n" % (os.path.join(root, xml_file)))
               log_file.close

【问题讨论】:

    标签: python xml directory-structure


    【解决方案1】:
    1. 在第二个循环之前测试目录名称是否合适。您必须首先获取路径中的最后一个目录。如:How to get only the last part of a path in Python?

      if os.path.basename(os.path.normpath(root)) == "bravo":
      
    2. 您可以使用https://docs.python.org/3/library/logging.html 模块进行日志记录。

    3. 如果你只想替换单个字母,那么也许你可以直接替换它而不是解析xml。如建议:https://stackoverflow.com/a/17548459/7062162

      def inplace_change(filename, old_string, new_string):
          # Safely read the input filename using 'with'
          with open(filename) as f:
              s = f.read()
              if old_string not in s:
                  print('"{old_string}" not found in  {filename}.'.format(**locals()))
                  return
      
          # Safely write the changed content, if found in the file
          with open(filename, 'w') as f:
              print('Changing "{old_string}" to "{new_string}" in {filename}'.format(**locals()))
              s = s.replace(old_string, new_string)
              f.write(s)
      

    【讨论】:

    • 谢谢大家...您的第 1 点很有效,我会阅读日志模块。
    猜你喜欢
    • 2012-10-28
    • 2014-11-07
    • 1970-01-01
    • 2013-09-22
    • 1970-01-01
    • 2021-04-07
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多