3

特定のディレクトリのファイル拡張子と各拡張子の数を出力しようとしています。

これは私がこれまでに持っているものです...

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( "。")のようなものを使おうとしましたが、行き詰まりました。拡張機能をリストに入れてからリストを数える必要があると思いますが、そこで問題が発生しています。

助けてくれてありがとう。

4

4 に答える 4

10

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)
于 2012-10-22T16:42:41.010 に答える
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)))
于 2012-10-22T16:46:17.690 に答える
1
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()
于 2018-04-22T09:50:35.237 に答える
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
于 2012-10-22T17:36:24.707 に答える