python计数文件和显示最大值
发布时间:2020-12-20 12:32:20 所属栏目:Python 来源:网络整理
导读:我想在一个目录中计算al文件范围.然后计算它们并显示它们中有多少.最好的方法是什么?这个脚本对于pdf = 0行代码来说真的很大. 另外,我如何显示从高到低的文件输出. import ospdf = 0doc = 0docx = 0xls = 0xlsx = 0ppt = 0pptx = 0for file in os.listdir("
我想在一个目录中计算al文件范围.然后计算它们并显示它们中有多少.最好的方法是什么?这个脚本对于pdf = 0行代码来说真的很大.
另外,我如何显示从高到低的文件输出. import os pdf = 0 doc = 0 docx = 0 xls = 0 xlsx = 0 ppt = 0 pptx = 0 for file in os.listdir("C:UsersjoeyDesktopschoolICOMMH"): if file.endswith(".pdf"): pdf += 1 print(file) if file.endswith(".doc"): doc += 1 print(file) if file.endswith(".docx"): docx += 1 print(file) if file.endswith(".xls"): xls += 1 print(file) if file.endswith(".xlsx"): xlsx += 1 print(file) if file.endswith(".ppt"): ppt += 1 print(file) if file.endswith(".pptx"): pptx += 1 print(file) print(pdf) print(doc) print(docx) 解决方法
你可以使用字典:
import os exts = {} my_exts = ('pdf','doc','docx','xls','xlsx','ppt','pptx') for file in os.listdir("C:UsersjoeyDesktopschoolICOMMH"): ext = os.path.splitext(file)[1] if ext and ext[1:] in my_exts: exts[ext] = exts.get(ext,0) + 1 print sorted(exts.items(),key=lambda x: x[1],reverse=True) 输出将是: [(‘.doc’,4),(‘.pdf’,2),(‘.xlsx’,1)] (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |