[英]What is the correct Python approach to avoid adding to the list in this script?
I am very new to Python, but I have read through the w3schools tutorial before starting out.我对 Python 很陌生,但在开始之前我已经通读了 w3schools 教程。
A recent web search led me to this helpful script which produces a JSON representation of a file tree.最近的 web 搜索使我找到了这个有用的脚本,它产生了文件树的 JSON 表示。
#!/usr/bin/env python
import os
import errno
def path_hierarchy(path):
hierarchy = {
'type': 'folder',
'name': os.path.basename(path),
'path': path,
}
try:
hierarchy['children'] = [
>>> path_hierarchy(os.path.join(path, contents))
for contents in os.listdir(path)
]
except OSError as e:
if e.errno != errno.ENOTDIR:
raise
if os.path.basename(path).endswith('doc') or os.path.basename(path).endswith('docx'):
hierarchy['type'] = 'file'
else:
+++ hierarchy = None
return hierarchy
if __name__ == '__main__':
import json
import sys
try:
directory = sys.argv[1]
except IndexError:
directory = "/home/something/something"
print(json.dumps(path_hierarchy(directory), indent=4, sort_keys=True))
I have 2 questions:我有两个问题:
At the position marked by ">>>", why doesn't the FOR statement precede the call to the method path_hierarchy ?在“>>”标记的 position 处,为什么 FOR 语句不在调用方法path_hierarchy 之前?
How do I avoid adding a hierarchy object for a file which is neither "doc" or "docx"?如何避免为既不是“doc”也不是“docx”的文件添加层次结构object? I experimented with setting the hierarchy object to None at the line marked "+++" but this simply returned a "null" in the JSON output.
我尝试在标记为“+++”的行将层次结构object 设置为None ,但这只是在 JSON output 中返回了一个“null”。 What I would like is no entry at all unless the current item is a folder or a type allowed by my test (in this case either 'doc' or 'docx')
我想要的是根本没有条目,除非当前项目是文件夹或我的测试允许的类型(在这种情况下是“doc”或“docx”)
For 1, that's a list comprehension.对于 1,这是一个列表理解。 They're used to build up a list from another list.
它们用于从另一个列表构建列表。
For 2, really, the problem here is you don't want None
s to be added to hierarchy['children']
.对于 2,实际上,这里的问题是您不希望将
None
添加到hierarchy['children']
。 This can be done a couple of different ways, but to do this, I'd just modify your >>>
line.这可以通过几种不同的方式完成,但要做到这一点,我只需修改您的
>>>
行。
If you have Python 3.8+, you can make use of an assignment expression ( :=
) , and add a if
check to the list comprehension:如果您有 Python 3.8+,则可以使用赋值表达式(
:=
) ,并在列表推导中添加一个if
检查:
hierarchy['children'] = [
child := path_hierarchy(os.path.join(path, contents))
for contents in os.listdir(path)
if child # Only add a child if the child is truthy (Not None)
]
Without Python 3.8, you need to convert that chunk to a full for
loop:如果没有 Python 3.8,您需要将该块转换为完整
for
循环:
hierarchy['children'] = []
for contents in os.listdir(path):
child = path_hierarchy(os.path.join(path, contents))
if child:
hierarchy['children'].append(child)
Both are essentially equivalent.两者本质上是等价的。
The takeaway here though is to just check what the child is before adding it to the tree.不过这里的要点是在将孩子添加到树之前检查它是什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.