如何将文件路径添加到 python 脚本

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 table)例如 -

<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')

这里有很多东西:

  1. AsGPhilo 在评论中说,考虑使用专用库来处理 XML 文件,最著名的是 lxml.
  2. 您应该排列 for inputfile in...with open(...) as out_file 以避免在每次迭代时 opening/closing 该文件
  3. 可以使用out_file.write(...)时不要使用print(..., file=...)

这是一个好的开始,您可能需要安排一下:

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)