打开嵌套文件结构中引用的文件

时间:2018-06-22 08:43:48

标签: python nested structure

我有一个xml文件结构,其中一个主xml引用其他一些xml文件(具有完整路径),而其他xml引用其他文件,依此类推。 我有很多xml文件(在一个简单的文件夹结构中,只有一个主文件夹和3个子文件夹),但并非所有xml文件都在其他xml文件中被引用,因此该想法是仅使用被引用的xml文件构建一个列表。 >

enter image description here

[编辑] 这是xml文件的非常简化的示例。 main.xml非常像这样。其他文件没有 children 标记,因此它们是嵌套参考行的结尾。

 <?xml version="1.0" encoding="UTF-8" ?>
 <file>
   <indiv>
        <name>Name Surname</name>
        <birth> Oct 1826 </birth>
        <death> Jan 1850 </death>        
   </indiv>
   <children>
        <chname1>Name1 Surname1</chname1>
        <chcode1>F45DH3</chcode1><chdata1>C:\base\codedb\F45DH3.xml</chdata1>
        <chname2>Name2 Surname2</chname2>
        <chdata2>C:\base\namedb\name2sur2.xml</chdata2>
   </children>
 </file>

[/ EDIT]

由于文件太多,无法手动检查,因此我想使用python脚本从主路径开始读取所有文件并构建列表。 我该怎么办。

到目前为止,这是我所拥有的,但是显然,编写这些代码很长,因为我不知道会找到多少级引用。 有想法吗?

coreFile= r"C:\\base\\main.xml"
xmlList = []

with open(coreFile) as f:
    for line in f:
        if "C:\\base" in line:
            start = line.find('C:\\base')
            end = line.find('.xml')
            path = line[start:end + 4]

            if path not in xmlList:
                x.append(path)
                with open(path) as f2:
                    for line2 in f2:
                        if "C:\\base" in line2:
                            start = line.find('C:\\base')
                            end = line.find('.xml')
                            path = line[start:end + 4]

                            if path not in xmlList:
                                x.append(path)
                                with open(path) as f3:
                                    # ...

1 个答案:

答案 0 :(得分:0)

所以我自己找到了答案。

万一它可以帮助别人,就像使用函数一样简单。

请记住,当并非文件夹结构中的所有文件都在其他文件中被引用时,此方法很有用,因此您需要阅读主文件并继续阅读下一级的引用文件。

如果要在文件夹结构的所有文件中查找文件引用,请忽略此。只需阅读文件夹和子文件夹中的每个文件即可。

def xmlRefs(filepath):
    with open(filepath) as f:
        for line in f:
            if "C:\\base" in line:
                start = line.find('C:\\base')
                end = line.find('.xml')
                path = line[start:end + 4]

                if path not in xmlList:
                    x.append(path)
                    xmlList.append(path)
                    print path
                    xmlRefs(path)

coreFile= r"C:\\base\\main.xml"
xmlList = []
xmlRefs(coreFile)