简体   繁体   English

避免添加到此脚本中的列表的正确 Python 方法是什么?

[英]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:我有两个问题:

  1. At the position marked by ">>>", why doesn't the FOR statement precede the call to the method path_hierarchy ?在“>>”标记的 position 处,为什么 FOR 语句不在调用方法path_hierarchy 之前

  2. 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.

相关问题 在 Python 中显示图像大小的正确方法是什么? - What is the correct approach to display the Image size in Python? Python:扁平化字典列表的最佳方法是什么 - Python: What is Best Approach for Flattening a list of Dictionary 正确的Python线程处理方法 - Correct Approach to Threading in Python 在Python中使用多处理,导入语句的正确方法是什么? - Using multiprocessing in Python, what is the correct approach for import statements? 这是包装脚本吗? 正确的名字是什么? (蟒蛇) - Is this a wrapper script? What is the correct name for it? (Python) 这种列表理解的正确python语法是什么? - What is correct python syntax for this kind of list comprehension? 用python将列表存储在驱动器上的最快方法是什么? - What is the fastest approach of having a list stored on drive in python? 在Python中重新分配列表的正确方法是什么? - What is the correct way to reassign a list in Python? Python 3.7:如何避免这种递归方法的计算器溢出? - Python 3.7: How to avoid stackoverflow for this recursive approach? 从 python 读取文件并添加到具有正确值类型的列表 - Reading files from python and adding to a list with correct value type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM