You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用单行代码实现仅将找到的文件添加至数组(去除空结果)

Solution to Filter Empty Glob Results in Your Python Code

Great question! You definitely can tweak your code to exclude those empty lists from the results. Let's go over a couple of ways to do this, depending on your desired output structure:

Option 1: Keep a List of Non-Empty Result Lists

If you want to retain the structure where each entry corresponds to a file in your input list (but only include entries where the file was found), you can use the walrus operator (:=) to capture the glob result and check if it's non-empty before adding it to the list:

import glob

files = ['text.txt', 'fdsafdsa.txt', 'example.txt']
def search_file(file_list):
    # Only include results where glob found something
    return [result for filename in file_list if (result := glob.glob(f'**/{filename}', recursive=True))]

found = search_file(files)
# Example output: [['path/to/text.txt'], ['path/to/example.txt']]

Option 2: Get a Flat List of All Found Files

If you just want a single list of all the actual file paths that were found (without grouping by the original filenames), use a nested list comprehension to flatten the results automatically—empty glob results will simply contribute nothing to the final list:

import glob

files = ['text.txt', 'fdsafdsa.txt', 'example.txt']
def search_file(file_list):
    # Iterate over each path from every successful glob search
    return [path for filename in file_list for path in glob.glob(f'**/{filename}', recursive=True)]

found = search_file(files)
# Example output: ['path/to/text.txt', 'path/to/example.txt']

Quick Notes:

  • Don't forget to import glob at the top of your script (it's missing in your original code snippet).
  • The walrus operator (:=) works in Python 3.8 and above—if you're using an older version, you can rewrite Option 1 like this instead (though it runs the glob search twice per filename, so it's less efficient):
    return [glob.glob(f'**/{filename}', recursive=True) for filename in file_list if glob.glob(f'**/{filename}', recursive=True)]
    

内容的提问来源于stack exchange,提问作者bas landman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 21:42:50