Python怎么获取当前目录指定扩展名的文件名

Python019

Python怎么获取当前目录指定扩展名的文件名,第1张

import os

import os.path

ext=input('请输入你要显示的文件扩展名(如.py):')

print([f for f in os.listdir() if os.path.isfile(f) and os.path.splitext(f)[1]==ext])

我写了个小文件,希望能帮到楼主

=========count_file.py=============

#coding:utf-8

import os

'''

使用os.walk()统计文件类型

'''

#定义result字典用来存储

result = {}

for directory, folders, files in os.walk('/home/zhulei'):

for f in files:

if '.' in f:

#获得文件类型

file_type = f.rsplit('.',1)[1]

if result.has_key(file_type):

result[file_type] += 1

else:

result[file_type] = 1

print "文件类型\t\t个数"

print "="*40

for type, count in sorted(result.items(),key=lambda x:x[1],reverse=True):

if len(type) >= 8:

print "%s\t\t%s" % (type, count)

else:

print "%s\t\t\t%s" % (type, count)

==============================

运行结果:

%python count_file.py

文件类型个数

========================================

png 2107

c 1639

h 1276

py 1160

gif 1017

svn-base966

TXT 899

jpg 831

html539

...

...

...

.py

.py文件是python的脚本文件,Python在执行时,会将.py文件中的源代码编译成Python的byte code,再由Python Virtual Machine来执行这些编译好的byte code。