[英]how to add file path in to python script
我有一个脚本,可以递归地研究给定目录,挖掘出具有特定文件名的所有文件,并将找到的所有文件的内容放入单个文件中。
在搜寻文件并将所有内容输出到单个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)
脚本查找的每个project_information.xml如下所示:
<project>
<name>project1</name>
<Projection>UTM84-30N</Projection>
<Build>Jan 30 2015</Build>
</project>
理想情况下,对于找到的每个条目,然后将其添加到我的输出中,我希望它在标记中写入文件路径。 (您可能会猜想这是要插入Excel的XML表),例如-
<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非常新,因此非常感谢我对原始代码的任何建议或更改!
############ UPDATE因此,正如@ 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=...)
out_file.write(...)
这是一个好的开始,您可能需要进行安排:
import glob
from lxml import etree
root = etree.Element("root")
with open ('D:\path\result\output.xml', 'w') as out_file:
for inputfile in glob.glob('D:\path\to\scan\**\project_information.xml', recursive=True):
with open (inputfile, "r") as in_file:
project = etree.SubElement(root, "project", path=in_file)
# ... continue with your processing
root.write(out_file, pretty_print=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.