python - 如何将文件树复制为 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 添加新的“文件夹”或“文档”。
有没有比嵌套列表更好/更有效的方法?
解决方案
使用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>
您可以尝试确定dir
orfile
是否应该是元素标记或属性。
推荐阅读
- clang-tidy - 这个 clang-tidy 命令行有什么问题?
- wso2 - WSO2 API 管理器 2.6:apimcli 导出 api 错误
- javascript - 使用 chrome.system.cpu 计算当前 CPU 使用率
- mysql - 将子查询转换为 MySQL 的 JOIN 语句?
- azure-devops - 阻止项目管理员向 Azure DevOps 中的项目和组织添加新用户?
- javascript - 如何避免必须对具有 2 个条件的 javascript 数组进行两次排序
- javascript - 似乎无法访问反应导航中的参数
- sql - 计算闰年月份的天数
- java - java中如何强制子类实现其非抽象、非接口实现的父类的方法?
- python-3.x - 基于月份和日期的多个 pandas 数据帧的叠加图