简体   繁体   English

使用过滤器和地图在目录中找到扩展名为.txt和.py的所有文件(使用python)

[英]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.

相关问题 在 Python 中查找扩展名为 .txt 的目录中的所有文件 - Find all files in a directory with extension .txt in Python 如何遍历 python 中的目录树并将扩展名为 .py 或 .txt 的文件添加到 zip 文件中。? - how to traverse a directory tree in python and those files which have extension of .py or .txt add them in a zipfile.? 为所有文件扩展名为“.py”的文件迭代一个目录 - Iterate a directory for all files with file extension '.py' 使用Python查找目录中的所有CSV文件 - Find all CSV files in a directory using Python 使用python从目录中的所有.txt文件中获取行 - Get rows from all .txt files in directory using python 使用 Python 写入目录中的所有 *.txt 文件 - Write in all the *.txt files within a directory using Python 如何找到一个目录下的.txt文件,并写入python中? - how to find .txt files in a directory, and write in it in python? 如何使用Python递归复制目录中具有特定扩展名的所有文件? - How to recursively copy all files with a certain extension in a directory using Python? 使用glob python读取具有特定扩展名的目录中的所有文件 - reading all the files in a directory with specific extension using glob python Python:将目录中的所有文件转换为一个 .TXT? - Python: Convert all files in directory into one .TXT?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM