我想在一个目录中计算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:\\Users\\joey\\Desktop\\school\\ICOMMH"):
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)
Run Code Online (Sandbox Code Playgroud)
这是你使用的地方 collections.defaultdict
from collections import defaultdict
import os.path
d = defaultdict(int)
for fname in os.listdir("C:\\Users\\joey\\Desktop\\school\\ICOMMH"):
_, ext = os.path.splitext(fname)
d[ext] += 1
Run Code Online (Sandbox Code Playgroud)
然后你最终得到一个字典,看起来像:
{'.pdf': 7, # or however many...
'.doc': 3,
'.docx': 2, ...}
Run Code Online (Sandbox Code Playgroud)
然后,您可以通过以下方式显示最常见的内容
max(d, key=lambda k: d[k])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
109 次 |
| 最近记录: |