【问题标题】:Python counting file extensionsPython 计算文件扩展名
【发布时间】:2012-10-22 16:40:22
【问题描述】:

我正在尝试打印某个目录中的文件扩展名以及每个扩展名的计数。

这就是我目前所拥有的......

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(".") 之类的东西,但我卡住了。我想我需要将扩展​​名放在一个列表中,然后对列表进行计数,但这就是我遇到问题的地方。

感谢您的帮助。

【问题讨论】:

标签: python


【解决方案1】:

使用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)))
    

    【讨论】:

      【解决方案3】:
      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()
      

      【讨论】:

        【解决方案4】:

        此实现将计算每个扩展的出现次数并将其放入变量 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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-11-22
          • 2021-02-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多