Python 统计文件扩展名

5
我正在尝试在特定目录中打印文件扩展名及每个扩展名的计数。
以下是我目前的代码...
import os 
import glob

os.chdir(r"C:\Python32\test")
x = glob.glob("*.*")
for i x:
    print(i)

>>> file1.py
    file2.py
    file3.py
    file4.docx
    file5.csv

所以我陷入了困境,我需要整体输出为...
py    3
docx  1
csv   1

我曾努力使用类似 i.split(".") 的方法,但我陷入了困境。我认为我需要将扩展名放入一个列表中,然后计算该列表的长度,但这就是我遇到问题的地方。
感谢您的帮助。

创建一个新的空字典,如果扩展不存在,则添加一个新条目并将值设置为1,如果已经存在,则将其增加1。 - TheZ
你确定以上代码不会出现“SyntaxError”吗? - Joel Cornett
4个回答

11
使用os.path.splitext函数来查找文件扩展名,然后使用collections.Counter函数计算扩展名的类型。
import os 
import glob
import collections

dirpath = r"C:\Python32\test"
os.chdir(dirpath)
cnt = collections.Counter()
for filename in glob.glob("*"):
    name, ext = os.path.splitext(filename)
    cnt[ext] += 1
print(cnt)

2

您可以使用collections.Counter

from collections import Counter
import os
ext_count = Counter((ext for base, ext in (os.path.splitext(fname) for fname in your_list)))

2
import collections
import os

cnt = collections.Counter()
def get_file_format_count():
    for root_dir, sub_dirs, files in os.walk("."):
        for filename in files:
            name, ext = os.path.splitext(filename)
            cnt[ext] += 1
    return cnt

print get_file_format_count()

0

这个实现将计算每个扩展名的出现次数并将其放入变量c中。通过在计数器上使用most_common方法,它将首先打印最常见的扩展名,就像您在示例输出中看到的那样。

from os.path import join, splitext
from glob import glob
from collections import Counter

path = r'C:\Python32\test'

c = Counter([splitext(i)[1][1:] for i in glob(join(path, '*'))])
for ext, count in c.most_common():
    print ext, count

输出

py 3
docx 1
csv 1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接