簡體   English   中英

如何在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表),例如-

<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. 正如GPhilo在評論中所說,請考慮使用專用庫來處理XML文件,最著名的是lxml
  2. 您應該將輸入文件置換for inputfile in...with open(...) as out_file以避免在每次迭代時打開/關閉此文件
  3. 可以使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM