在目录中查找名为 *.txt 的所有文件

Find all files named *.txt in directory

import os, glob

file = os.listdir("my directory: example")

mp3files = list(filter(lambda f: f == '*.txt',file))    
print(mp3files)

此代码仅提供给我:[]

mp3files = list(filter(lambda f: f.endswith('.txt') ,file))

应该可以,因为文件名与 *.txt 不匹配 (==),而是以该扩展名结尾

使用str.endswith:

list(filter(lambda f: f.endswith('.txt'),file))

你为什么不使用你导入的 glob 模块?

mp3files = glob.glob('*.txt')

这将 return 当前工作目录中所有 mp3 文件的列表。 如果您的文件在不同的目录中而不是在您的 cwd 中:

path_to_files_dir = os.path.join(os.getcwd(), 'your_files_dir_name', '*.txt')

mp3files = glob.glob(path_to_files)

从 Python 3.4 开始,您可以只使用这两行来完成该任务:

from pathlib import Path
mp3files = list(Path('.').glob('**/*.txt'))

更多信息:https://docs.python.org/3/library/pathlib.html