简体   繁体   中英

Find all files in directory with extension .txt and .py with python using filter and map

如何使用filter和map函数在Python中以.txt.py结尾的目录中找到文件?

os.listdir will get you a listing of the files. Then you just need to write a function which returns True when the filename endswith .py or .txt :

filter(lambda x: x.endswith(('.txt','.py')), os.listdir(os.curdir))

... I really don't know how to incorporate map into it ...

您也可以尝试类似列表的理解

[x for x in os.listdir(os.curdir) if os.path.splitext(x)[1] in ('.txt', '.py')]

Here are two ways:

A pure functional approach:

from operator import methodcaller
filter(methodcaller('endswith', ('.txt', '.py')), os.listdir('.'))

A list comprehension approach:

[fn for fn in os.listdir('.') if fn.endswith(('.txt', '.py'))]

Hope this helps :-)

you can use glob module to get those files

>>> import glob    
>>> glob.glob('*.py')
['test.py', 'a.py', 'b.py']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM