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

Python 在目录中查找名为*.txt的所有文件,python,filenames,glob,Python,Filenames,Glob,此代码仅为我提供:[] import os, glob file = os.listdir("my directory: example") mp3files = list(filter(lambda f: f == '*.txt',file)) print(mp3files) 应该可以工作,因为文件名与*.txt不匹配(=),而是以该扩展名结尾使用str.endswith: mp3files = list(filter(lambda f: f.endswith('.txt') ,

此代码仅为我提供:
[]

import os, glob

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

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

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

使用
str.endswith

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

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

list(filter(lambda f: f.endswith('.txt'),file))
这将返回当前工作目录中所有mp3文件的列表。 如果您的文件位于其他目录而不在cwd中:

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

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

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

mp3files = glob.glob(path_to_files)

更多信息:

提示:使用您要导入的
glob
模块。:)您的
lambda f:f='*.txt'
实际上是在比较每个文件名,看它是否匹配.txt,因此它们都失败了,您得到了空列表。*仅当某些函数(如regex、string、glob等)将其视为通配符时,才是通配符。否则就是字面意思了*非常感谢,我真的很感谢帮助很好的解决方案,但他正在寻找*.txt文件。是的,没错,我已经将扩展名从mp3改为txt,谢谢我知道glob,但我的任务是使用函数filter和lambda
from pathlib import Path
mp3files = list(Path('.').glob('**/*.txt'))