我有一个脚本,它递归地深入到给定的目录中,挖掘出具有特定文件名的所有文件,并将找到的所有文件的内容放入单个文件中。你知道吗
在查找文件并将所有内容输出到单个xml文件方面,脚本按我的需要工作。但是,我想它添加在文件路径,以便我知道它找到的每个给定文件的位置。这是我目前的代码:
import glob
lines=[] #list
for inputfile in glob.glob('D:\path\to\scan\**\project_information.xml', recursive=True):
with open ('D:\path\result\output.xml', 'w') as out_file:
with open (inputfile, "rt") as in_file:
print("<projectpath>", inputfile, file=out_file)
for line in in_file:
lines.append(line.rstrip('\n'))
for linenum, line in enumerate(lines):
print(line, file=out_file)
每个项目_信息.xml脚本将查找以下内容:
<project>
<name>project1</name>
<Projection>UTM84-30N</Projection>
<Build>Jan 30 2015</Build>
</project>
理想情况下,对于找到并随后添加到输出中的每个条目,我希望它在标记中写入文件路径。(您可能猜到这是一个XML表,可以放入Excel)例如-
<project>
**<filepath>C:\path\to\file\**
<name>project1</name>
<Projection>UTM84-30N</Projection>
<Build>Jan 30 2015</Build>
</project>
<project>
**<filepath>C:\path\to\file\blah\**
<name>project2</name>
<Projection>UTM84-30N</Projection>
<Build>Jan 30 2015</Build>
</project>
我认为在with语句后添加一行就可以了,但它只会打印第一个引用,而不会进入循环中——不仅如此,即使这样做有效,它也不会在父标记中。你知道吗
print("<projectpath>", inputfile, file=out_file)
非常新的python,所以任何建议或修改我的粗代码非常感谢!你知道吗
############更新因此,正如@olinox14所建议的,我查看了lxml模块,并让它添加一个新的标签。你知道吗
tree = ET.parse(in_file)
root = tree.getroot()
for child in root:
folder = ET.SubElement(child, 'folder')
folder.text = (in_file.name)
tree.write('C:\\output\\output2.xml')
这里有很多东西:
for inputfile in...
和with open(...) as out_file
,以避免每次迭代时打开/关闭此文件out_file.write(...)
时,不要使用print(..., file=...)
这是一个良好的开端,您可能需要安排:
相关问题 更多 >
编程相关推荐