Py学习  »  Python

python for loop只将最后一个列表作为值追加

Sascha • 5 年前 • 428 次点击  

我在一个目录中循环,希望将文件夹中的所有文件作为列表存储在字典中,其中每个键都是一个文件夹和文件列表的值。

循环中的第一次打印正好显示了我所期望的输出。

但是,第二次打印显示空值。

类初始化后的第三次打印将最后一个子文件夹的列表显示为每个键的值。

我忽略了什么或做错了什么?

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社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/41047
 
428 次点击  
文章 [ 3 ]  |  最新文章 5 年前