python 获取文件后缀名

2025-03-24 09:46:41
推荐回答(4个)
回答1:

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

=========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-base 966
TXT 899
jpg 831
html 539

...
...
...

回答2:

#!/usr/bin/python

import os

dict = {}
for d, fd, fl in os.walk('/home/ahda/Program/'):
for f in fl:
sufix = os.path.splitext(f)[1][1:]
if dict.has_key(sufix):
dict[sufix] += 1
else:
dict[sufix] = 1

for item in dict.items():
print "%s : %s" % item

这里的关键是os.path.splitext()
这是跟楼上不同的地方。如abc/ef.g.h
楼上出来的后缀会是g.h
而我的是h

回答3:

程序代码如下所示:

import os
dict = {}
for d, fd, fl in os.walk(r"F:\\"):
    for f in fl:
        sufix = os.path.splitext(f)[1][1:]
        if dict.has_key(sufix):
            dict[sufix] += 1
        else:
            dict[sufix] = 1

for item in dict.items():
    print "%s : %s" % item
  1. 第二行:创建一个字典用来保存文件后缀名及个数;

  2. 第三行:循环的目的主要就是os.path.splitext()分离后缀名和文件名;

  3. 最后打印输出。

回答4:

写循环啊 哥哥