首页 > 解决方案 > 计算目录中同名的多个文件

问题描述

我对 Python 比较陌生,并且正在开发一个用户可以导航到文件夹的项目,之后程序会计算该文件夹中具有特定名称的所有文件。

问题是我有一个包含 5000 多个文件的文件夹,其中许多文件共享相同的名称但扩展名不同。我编写的代码在某种程度上做了我希望最终版本做的事情,但它非常多余,我看不到自己为超过 600 个文件名这样做。

想问是否有可能使这个程序“自动化”或减少冗余,我不必手动输入 600 个文件的名称来返回数据。

我目前拥有的示例代码:

import os, sys
print(sys.version)

file_counting1 = 0
file_counting2 = 0

filepath = input("Enter file path here: ")

if os.path.exists(filepath):

    for file in os.listdir(filepath):
        if file.startswith('expressmail'):
            file_counting1 += 1
    print('expressmail')
    print('Total files found:', file_counting1)

    for file in os.listdir(filepath):
        if file.startswith('prioritymail'):
            file_counting2 += 1
    print('prioritymail')
    print('Total files found:', file_counting2)

样本输出:

expressmail
Total files found: 3
prioritymail
Total files found: 1

标签: python-3.xglobos.path

解决方案


有很多方法可以让你做你想做的事。部分取决于您是否需要恢复给定重复文件的扩展名列表。

  1. 来自集合模块的计数器 - 将其用于简单的文件计数。构建计数时忽略扩展。
  2. 使用不带扩展名的文件名作为字典键,添加项目列表作为键值,其中项目列表是文件的每次出现。

下面是一个使用 Counter 类的示例:

import os, sys, collections
c = collections.Counter()
for root, dirs,files in os.walk('/home/myname/hg/2018/'):
    # discard any path data and just use filename
    for names in files:
        name, ext = os.path.splitext(names)
        # discard any extension
        c[name] += 1
# Counter.most_common() gives the values in the form of (entry, count)
# Counter.most_common(x) - pass a value to display only the top x counts
# e.g. Counter.most_common(2) = top 2
for x in c.most_common():
    print(x[0] + ': ' + str(x[1]))

推荐阅读