如何在python脚本中添加文件路径

2023-09-22 18:23:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个脚本,它递归地深入到给定的目录中,挖掘出具有特定文件名的所有文件,并将找到的所有文件的内容放入单个文件中。你知道吗

在查找文件并将所有内容输出到单个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')

Tags: 文件pathnameinbuildproject脚本for
1条回答
网友
1楼 · 发布于 2023-09-22 18:23:34

这里有很多东西:

  1. AsGPhilo在评论中说,考虑使用一个专用库来处理XML文件,最有名的是lxml。你知道吗
  2. 应该排列for inputfile in...with open(...) as out_file,以避免每次迭代时打开/关闭此文件
  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)

相关问题 更多 >