我想采用單個檔案夾路徑(根),然后將所有檔案路徑放入類似于原始目錄結構的字典中。
例如:我有一個看起來像這樣的檔案夾:
root
-sub1
--someFile.txt
--someFile2.txt
-sub2
--subsub1
---veryNested.txt
--someFile3.txt
-someFile4.txt
我希望字典看起來像這樣:
{'root': {
'.dirs': {
'sub1':{
'.dirs':{},
'.files':['someFile.txt', 'someFile2.txt']
},
'sub2':{
'.dirs':{
'subsub1':{
'.dirs':{},
'.files':['veryNested.txt']
}
},
'.files':['someFile3.txt']
}
},
'.files':['someFile4.txt']
}
我一直在環顧四周,我真的找不到這個問題的一個很好的通用答案。有人可以向我指出一些好的資源,或者對代碼的外觀進行簡要而概括的解釋嗎?我想在沒有人 100% 握住我的手的情況下解決這個問題,或者只是給我解決方案。如果需要更多說明,請告訴我!
uj5u.com熱心網友回復:
有很多方法可以獲得目錄結構的表示。
以下功能使用遞回方法將您的目錄結構列出到 json 物件中:
import os
import json
def path_to_dict(path):
d = {'name': os.path.basename(path)}
if os.path.isdir(path):
d['type'] = "folder"
d['content'] = [path_to_dict(os.path.join(path, x)) for x in os.listdir(path)]
else:
d['type'] = "file"
return d
# string rapresentation
dict_tree = json.dumps(path_to_dict('C:/Users/foo/Desktop/test'))
# convert in json
json = json.loads(dict_tree )
輸出:
{'name': 'test',
'type': 'folder',
'content': [{'name': 'subfolder_1',
'type': 'folder',
'content': [{'name': 'test_file_1.txt', 'type': 'file'},
{'name': 'test_file_2.txt', 'type': 'file'}]},
{'name': 'subfolder_2',
'type': 'folder',
'content': [{'name': 'test_file_3.txt', 'type': 'file'}]}]}
額外:如果您在 Linux 機器上作業,您可以使用tree工具獲得相同的效果。為了列出特定目錄的檔案和子檔案夾,您可以通過以下命令語法指定目錄名稱或路徑:
tree -J folder_name
-J 引數用于 json 表示。
uj5u.com熱心網友回復:
以下代碼將目錄路徑轉換為可讀字典:
感謝@BlackMath為我指明了正確的方向!
import os
from os import path
def dirToDict(dirPath):
d = {}
for i in [os.path.join(dirPath, i) for i in os.listdir(dirPath) if os.path.isdir(os.path.join(dirPath, i))]:
d[os.path.basename(i)] = dirToDict(i) # You can remove the 'basename' to get the full directory path
d['.files'] = [i for i in os.listdir(dirPath) if os.path.isfile(os.path.join(dirPath, i))] # You can add a os.path.join(dirPath, i) here to get full file name
return d
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/322857.html
上一篇:創建具有多個值的字典
