[英]Python: os.listdir alternative/certain extensions
是否可以使用 os.listdir 命令查看具有某些扩展名的文件? 我希望它可以工作,因此它可能只显示结尾带有 .f 的文件或文件夹。 我查看了文档,没有发现任何内容,所以不要问。
glob
擅长于此:
import glob
for f in glob.glob("*.f"):
print(f)
不要问什么?
[s for s in os.listdir() if s.endswith('.f')]
如果你想检查一个扩展列表,你可以做一个明显的概括,
[s for s in os.listdir() if s.endswith('.f') or s.endswith('.c') or s.endswith('.z')]
或者另一种方式写起来更短:
[s for s in os.listdir() if s.rpartition('.')[2] in ('f','c','z')]
还有一种目前没有提到的可能性:
import fnmatch
import os
for file in os.listdir('.'):
if fnmatch.fnmatch(file, '*.f'):
print file
实际上这就是glob
模块的实现方式,所以在这种情况下glob
更简单更好,但是fnmatch
模块在其他情况下可以很方便,例如使用os.walk
进行树遍历时。
尝试这个:
from os import listdir
extension = '.wantedExtension'
mypath = r'my\path'
filesWithExtension = [ f for f in listdir(mypath) if f[(len(f) - len(extension)):len(f)].find(extension)>=0 ]
[s for s in os.listdir() if os.path.splitext(s) == 'f']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.