首页 > 解决方案 > 如何将文件树复制为 Python 列表?

问题描述

我需要将文件目录树的功能复制为列表。我必须能够通过“文件夹”搜索特定的“文档”。所有这些都可能包含其他深度的重复名称。我还必须能够在运行时动态添加新文件和文件夹。例如,像这样的文件树:

MyFiles
    Important
        doc1
        doc2
    LessImportant
        doc3
        doc4
    LowPriority
        Important
            doc1
        LessImportant
            doc4

如果我使用嵌套列表,上面的树最终看起来像:

[MyFiles,[Important,[doc1,doc2],LessImportant,[doc3,doc4],LowPriority, 
[Important,[doc1],LessImportant,[doc4]]]]

然后我必须在所有嵌套中运行循环来搜索东西并使用 .append 添加新的“文件夹”或“文档”。

有没有比嵌套列表更好/更有效的方法?

标签: pythonlistfiledirectory

解决方案


使用ElementTree提供了搜索和迭代功能。

import os
import xml.etree.ElementTree as ET

def ls(p):
    if os.path.isdir(p):
        node = ET.Element(os.path.basename(p), type='dir')
        node.extend([ls(os.path.join(p, f)) for f in os.listdir(p)])
    else:
        node = ET.Element(os.path.basename(p), type='file')
    return node

然后通过写出 XML 来测试它,因为这在 ElementTree 中很容易:

root = ET.ElementTree(ls(r"C:\test\Myfiles"))

from xml.dom import minidom
def pp(tree):
    print ''.join(minidom.parseString(ET.tostring(tree.getroot())).toprettyxml(indent='  ').splitlines(True)[1:])

pp(root)

<Myfiles type="dir">
  <Important type="dir">
    <doc1 type="file"/>
    <doc2 type="file"/>
  </Important>
  <LessImportant type="dir">
    <doc1 type="file"/>
    <doc2 type="file"/>
  </LessImportant>
  <LowPriority type="dir">
    <Important type="dir">
      <doc1 type="file"/>
    </Important>
    <LessImportant type="dir">
      <doc4 type="file"/>
    </LessImportant>
  </LowPriority>
</Myfiles>

您可以尝试确定dirorfile是否应该是元素标记或属性。


推荐阅读