[英]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. os.listdir
将为您提供文件列表。 Then you just need to write a function which returns True
when the filename endswith .py
or .txt
: 然后,您只需要编写一个函数,当文件名以
.py
或.txt
结尾时返回True
:
filter(lambda x: x.endswith(('.txt','.py')), os.listdir(os.curdir))
... I really don't know how to incorporate map
into it ... 我真的不知道如何将
map
纳入其中
您也可以尝试类似列表的理解
[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 您可以使用glob模块获取这些文件
>>> import glob
>>> glob.glob('*.py')
['test.py', 'a.py', 'b.py']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.