【发布时间】:2019-07-08 15:24:53
【问题描述】:
我正在遍历一个目录,并希望将文件夹中的所有文件存储为字典中的列表,其中每个键是一个文件夹,文件列表是值。
循环中的第一个打印准确地显示了我期望的输出。
但是第二个打印显示空值。
类初始化后的第三次打印显示最后一个子文件夹的列表作为每个键的值。
我忽略了什么或做错了什么?
class FileAndFolderHandling() :
folders_and_files = dict()
def __init__(self) :
self.getSubfolderAndImageFileNames()
def getSubfolderAndImageFileNames(self) :
subfolder = ""
files_in_subfolder = []
for filename in glob.iglob('X:\\Some_Directory\\**\\*.tif', recursive=True) :
if not subfolder == os.path.dirname(filename) and not subfolder == "" :
print(subfolder + " / / " + str(files_in_subfolder))
self.folders_and_files[subfolder] = files_in_subfolder
files_in_subfolder.clear()
print(self.folders_and_files)
subfolder = os.path.dirname(filename) # new subfolder
files_in_subfolder.append(os.path.basename(filename))
folder_content = FileAndFolderHandling()
print(folder_content.folders_and_files)
【问题讨论】:
标签: python loops dictionary for-loop append