如何用单行代码实现仅将找到的文件添加至数组(去除空结果)
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 globat 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

