【发布时间】:2011-03-08 13:00:29
【问题描述】:
是否可以使用 os.listdir 命令查看具有特定扩展名的文件?我希望它能够工作,因此它可能只显示最后带有 .f 的文件或文件夹。查了文档,没找到,别问了。
【问题讨论】:
是否可以使用 os.listdir 命令查看具有特定扩展名的文件?我希望它能够工作,因此它可能只显示最后带有 .f 的文件或文件夹。查了文档,没找到,别问了。
【问题讨论】:
glob 擅长这个:
import glob
for f in glob.glob("*.f"):
print(f)
【讨论】:
试试这个:
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 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')]
【讨论】:
lambda。这是我最喜欢 Python 的地方之一。
[s in os.listdir() if s.endswith('.f')] 在此处使用 Python 2.7 会导致语法错误。 [s for s in os.listdir('.') if s.endswith('.f')] 工作
[s for s in os.listdir() if os.path.splitext(s) == 'f']
【讨论】:
os.path.splitext(s)[1] == '.f'。
还有一种可能性目前没有提到:
import fnmatch
import os
for file in os.listdir('.'):
if fnmatch.fnmatch(file, '*.f'):
print file
其实glob模块就是这样实现的,所以在这种情况下glob更简单更好,但是fnmatch模块在其他情况下可以很方便,例如使用os.walk 进行树遍历时。
【讨论】: