每日小窍门:在python中如何判断文件的文件类型?

每日小窍门:在python中如何判断文件的文件类型?,第1张

我和辩们会遇到一种情况,需要来判断输入文件的类型,在python中我们可以使用 mime 包:

安装:

测试:

我们将得到下面的输出结果:

我们可以看到,mime这个包可以帮袭前助唤禅缺我们判断文件类型

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

=========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

...

...

...

#已知搭做姿文件名的情况下,胡枣可以用知绝这个函数

def getFileInfo(filepath):

info = {}

if os.path.isfile(filepath):

info['TimeCreated'] = os.path.getctime(filepath)

info['TimeModified'] = os.path.getatime(filepath)

info['Size'] = os.path.getsize(filepath)

return info


欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/tougao/12120064.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-21
下一篇 2023-05-21

发表评论

登录后才能评论

评论列表(0条)

保存