猿问

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

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

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


 <?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>

由于文件太多,无法手动检查,因此我想使用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:

                                    # ...


慕桂英546537
浏览 156回答 1
1回答

慕尼黑5688855

所以我自己找到了答案。万一它可以帮助别人,就像使用一个函数一样简单。请记住,当并非文件夹结构中的所有文件都在其他文件中被引用时,此方法很有用,因此您需要阅读主文件并继续阅读下一级的引用文件。如果要在文件夹结构中的所有文件中查找文件引用,请忽略此操作。只需读取文件夹和子文件夹中的每个文件。def xmlRefs(filepath):&nbsp; &nbsp; with open(filepath) as f:&nbsp; &nbsp; &nbsp; &nbsp; for line in f:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if "C:\\base" in line:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; start = line.find('C:\\base')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; end = line.find('.xml')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; path = line[start:end + 4]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if path not in xmlList:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; x.append(path)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; xmlList.append(path)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print path&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; xmlRefs(path)coreFile= r"C:\\base\\main.xml"xmlList = []xmlRefs(coreFile)
随时随地看视频慕课网APP

相关分类

Python
我要回答