我正在尝试使用字典根据扩展名对目录中的文件进行分组,但我的代码没有按预期行为。我有几个以.mp4
结尾的视频文件,我有一个脚本,可以获得文件的扩展名,然后检查它是否作为字典中的键存在。
注:
Dictionary holds extensions as keys and all the files with the extension as items
.
如果extension作为键存在于字典中,则将当前文件名添加到与该键关联的项中。如果它不存在,则在字典中创建一个新的键项,其中包含空项。我的代码正在打印字典的元素,如下所示
'.mp4': 'Edited_20220428_154134.mp4', '.png': 'folder_icon.png',
您可以从上面的输出中看到,我的代码确实有扩展名作为键,但对于视频,当该文件夹中有几个视频时,它只包含一个项目,我需要帮助使它成为扩展名的关键,并将具有该扩展名的所有文件名添加到与该键相关的项目。下面是我的代码
#import the os module
import os
# define the path to the documents folder
path = "C:\Users\USER\Documents"
# list all the files in the directory
files = os.listdir(path)
# sort the files lexicographically
files.sort()
# code to ask user to choose file operation, in this context user chooses group by extension
# code omitted for MRE purposes
print("Grouping the files by extension")
# initialize the dictionary for holding the extension names
extensions = {}
# iterate through each file name and split the name to get file name and extension as a tuple
for file in files:
ext = os.path.splitext(file)[1]
if ext not in extensions.keys(): # if the key extension does not exist add the key to the dict as a new entry
extensions[ext] = file
else: # if the extension already append the item to the key items
extensions[ext] = file
#print the dict to check if the operation was succesful
print(extensions)
试试这个:
for file in files:
ext = os.path.splitext(file)[1]
if ext not in extensions.keys():
extensions[ext] = [file]
else:
extensions[ext].append(file)
如果发现扩展名为extensions[ext] = file
,则覆盖所有文件。=
正在将该字典项设置为单个文件的值。
在上面的代码中,您在第一次找到扩展名时创建一个列表。在那之后的每一次你都要添加到列表中。
if ext not in extensions.keys():
extensions[ext] = file
else: # if the extension already append the item to the key items
extensions[ext] = file
您正在覆盖而不是追加字典中的值。尝试使用:
if ext not in extensions.keys():
extensions[ext] = file
else: # if the extension already append the item to the key items
extensions[ext] += [file]
使用+=
附加所需文件名的操作符。如果您想对目录
中相似的文件名进行分组,请尝试此操作。import glob
x=glob.glob(_filepath_)
dictionary={}