我正在嘗試根據使用字典的擴展名對目錄中的檔案進行分組,但我的代碼沒有按預期運行。我有幾個以 結尾的視頻檔案.mp4,我有一個獲取檔案擴展名的腳本,然后檢查它是否作為字典中的鍵存在。
注意:
Dictionary holds extensions as keys and all the files with the extension as items.
如果擴展名作為字典中的鍵存在,則它將當前檔案名添加到與該鍵關聯的專案中。如果它不存在,則在字典中創建一個帶有空項的新鍵條目。我的代碼正在列印字典的元素,如下所示
'.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)
uj5u.com熱心網友回復:
嘗試這個:
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。就是=將該字典項設定為一個單一檔案的值。
在我上面的代碼中,您在第一次找到擴展名時創建了一個串列。之后每次都添加到串列中。
uj5u.com熱心網友回復:
通過做
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]
使用 =運算子附加所需的檔案名。
uj5u.com熱心網友回復:
如果要對目錄中相似的檔案名進行分組,請嘗試此操作
import glob
x=glob.glob(_filepath_)
dictionary={}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/488133.html
