python-3.x - 计算目录中同名的多个文件
问题描述
我对 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
解决方案
有很多方法可以让你做你想做的事。部分取决于您是否需要恢复给定重复文件的扩展名列表。
- 来自集合模块的计数器 - 将其用于简单的文件计数。构建计数时忽略扩展。
- 使用不带扩展名的文件名作为字典键,添加项目列表作为键值,其中项目列表是文件的每次出现。
下面是一个使用 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]))
推荐阅读
- python - 使用傅里叶变换的逆滤波器
- javascript - 如何让函数返回一个承诺
- python - 如何查询 DynamoDB 中一列的所有行?
- ajax - 我在 ajax 或 django 中的代码中的错误在哪里?
- generics - 如何使用 kotlin 泛型避免类型不匹配错误?
- cron - APScheduler:完成前一个作业后触发新作业
- php - 使用 jquery 和 php 的依赖国家/地区城市下拉列表中的问题
- javascript - 对象的方法在对象上被调用,何时存储在变量中,而不是当对象存储在数组中时
- angular - Angular Leaflet - 地图无法正确渲染
- installshield - Installshield 为次要升级引发错误“新版本已存在”