Python 3.x 计算目录中具有相同名称的多个文件
我对Python比较陌生,正在从事一个项目,在这个项目中,用户可以导航到一个文件夹,然后程序会对该文件夹中具有特定名称的所有文件进行计数 问题是我有一个包含5000多个文件的文件夹,其中许多文件共享相同的名称,但扩展名不同。我编写的代码在某种程度上实现了我想要的最终版本的功能,但它非常冗余,我无法看到自己对600多个文件名执行此操作 想问一下,如果我不需要手动键入600个文件的名称来返回数据,是否可以使这个程序“自动化”或减少冗余 我目前拥有的示例代码:Python 3.x 计算目录中具有相同名称的多个文件,python-3.x,glob,os.path,Python 3.x,Glob,Os.path,我对Python比较陌生,正在从事一个项目,在这个项目中,用户可以导航到一个文件夹,然后程序会对该文件夹中具有特定名称的所有文件进行计数 问题是我有一个包含5000多个文件的文件夹,其中许多文件共享相同的名称,但扩展名不同。我编写的代码在某种程度上实现了我想要的最终版本的功能,但它非常冗余,我无法看到自己对600多个文件名执行此操作 想问一下,如果我不需要手动键入600个文件的名称来返回数据,是否可以使这个程序“自动化”或减少冗余 我目前拥有的示例代码: import os, sys print
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
你有很多方法可以做你想做的事情。部分取决于是否需要恢复给定重复文件的扩展名列表
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]))
以下脚本将统计同名文件的出现次数。如果文件没有扩展名,则整个文件名将被视为名称。它也不会遍历子目录,因为原始问题只询问给定文件夹中的文件
import os
dir_name = "."
files = next(os.walk(dir_name))[2] # get all the files directly in the directory
names = [f[:f.rindex(".")] for f in files if "." in f] # drop the extensions
names += [f for f in files if "." not in f] # add those without extensions
for name in set(names): # for each unique name-
print("{}\nTotal files found: {}".format(name, names.count(name)))
如果您想支持子目录中的文件,可以使用
files = [os.path.join(r,file) for r,d,f in os.walk(dir_name) for file in f]
如果您不想考虑没有扩展名的文件,只需删除行:
names += [f for f in files if "." not in f]
您可以使用正则表达式:
import os, sys, re
print(sys.version)
filepath = input("Enter file path here: ")
if os.path.exists(filepath):
allfiles = "\n".join(os.listdir(filepath))
file_counting1 = len(re.findall("^expressmail",allfiles,re.M))
print('expressmail')
print('Total files found:', file_counting1)
file_counting2 = len(re.findall("^prioritymail",allfiles,re.M))
print('prioritymail')
print('Total files found:', file_counting2)
您是否有一个预先列出的600个文件名的列表,或者您的程序是否应该动态构建这样一个列表?您的硬编码名称建议使用前者,但您似乎希望使用后者。我确实继续分析了文件夹以提取文件名,结果显示有648个名称。我希望它能在运行中构建一个,但我不确定哪一个更容易实现。对同一件事进行648次硬编码似乎有点过分。