python 获取文件后缀名
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 获取文件后缀名相关的知识,希望对你有一定的参考价值。
自己写的太多漏洞和错误,就不贴出来了。要求是这样的,再此请教大家:
1.用os.walk() 分别遍历每个盘(并能判断电脑上有哪几个盘,并分别遍历)
2.获取盘内所有文件的后缀 (比如 .txt 遇到一个,则 count+=1 计数),并分别计数。
3.把刚才统计的类型和个数打印出来
比如
txt 523个
mp3 42个
py 12个
请帮忙写下,或者把关键函数和要点写下也可以。感谢
谢谢各位的回答,不过我发现用re正则式更好。因为有些文件是没有后缀名的。
=========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
...
...
... 参考技术A #!/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本回答被提问者采纳 参考技术B
程序代码如下所示:
import osdict =
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
第二行:创建一个字典用来保存文件后缀名及个数;
第三行:循环的目的主要就是os.path.splitext()分离后缀名和文件名;
最后打印输出。
获取文件路径文件名后缀名
#########start 获取文件路径、文件名、后缀名############ from gevent import os def jwkj_get_filePath_fileName_fileExt(filename): (filepath,tempfilename) = os.path.split(filename); (shotname,extension) = os.path.splitext(tempfilename); return filepath,shotname,extension #########end 获取文件路径、文件名、后缀名############ print(jwkj_get_filePath_fileName_fileExt("D:/保存的图片/571711894929.png"))
输出结果:(‘D:/保存的图片‘, ‘571711894929‘, ‘.png‘)
以上是关于python 获取文件后缀名的主要内容,如果未能解决你的问题,请参考以下文章