列出目录python中的扩展名

2024-10-08 19:22:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道^{cd1>}列出目录中的所有文件,并且^{{cd2>}可以找到具有特定扩展名的所有文件。还有一个超级简单的方法来列出目录中的所有扩展吗。 理想情况下,类似: os.listextension(direct)

Output: 
*.png
*.mat
*.csv
...

Tags: 文件csv方法目录outputpngos情况
3条回答
  1. 查找当前目录匹配模式中的所有文件(全球)
  2. 迭代并拆分“.”(map,split)上的每个条目。在
  3. 取每个迭代项的最后一个索引(index-1)。在
  4. 获取唯一列表(集合)。在

set(map(lambda x: x.split(".")[-1], glob.glob(".")))

样本输出

['sqlite', 'bat', 'py', 'gz', 'json', 'sh', 'tcl', 'txt', 'png']

非常简单的方法:

import fnmatch, os
print [i.split('.', 1)[1] for i in fnmatch.filter(os.listdir("path"), "*.*")]

输出:

^{pr2}$

您可以将生成器理解与os.path.splitext结合使用,以生成所有扩展的集合:

set(os.path.splitext(file)[-1] for file in os.listdir(path))

样本输出:

^{pr2}$

相关问题 更多 >

    热门问题