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

时间:2019-03-12 09:41:52

标签: python extract filepath glob

我有一个脚本可以递归地进入给定目录,挖掘出具有特定文件名的所有文件,并将找到的所有文件的内容放入一个文件中。

该脚本按我需要的方式工作,以搜寻文件并将所有内容输出到单个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')

1 个答案:

答案 0 :(得分:0)

这里有很多东西

  1. AsGPhilo在评论中说,考虑使用专用的库来处理XML文件,最著名的是lxml
  2. 您应该对function APIRequest($zip) { $URL = "http://www.example.com"; $options = array( CURLOPT_RETURNTRANSFER => true, // return web page CURLOPT_HEADER => false, // don't return headers CURLOPT_FOLLOWLOCATION => true, // follow redirects CURLOPT_ENCODING => "", // handle compressed CURLOPT_USERAGENT => "test", // name of client CURLOPT_AUTOREFERER => true, // set referrer on redirect ); $ch = curl_init($URL); curl_setopt_array($ch, $options); $response = curl_exec($ch); curl_close($ch); $xml = simplexml_load_string(utf8_encode($response)); $json = json_encode($xml); $json_response = json_decode($result); return $json_response; } for inputfile in...进行置换,以避免在每次迭代时打开/关闭该文件
  3. 可以使用with open(...) as out_file时不要使用print(..., file=...)

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

out_file.write(...)