【发布时间】: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 文件时,它会出错,因为这些文件不包含“文件”标签。
请有人帮我更正我的脚本(或创建一个新脚本)。
这里是一个文件夹结构的例子……
到目前为止,我的脚本...
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