1

我正在使用 python 和 PyQt5 库来显示所需路径中存在的目录和文件的列表。

用户选择所需的文件夹,程序创建一个包含所有现有文件夹和子文件夹和文件的列表,然后将此列表附加到 QlistWidget 以显示所有文件夹。

在此处输入图像描述

我想要的是将此列表转换为 TreeList 以使显示如下:

folder1 
   subfolder1
      file1
      file2
folder2
   subfolder1
      file1
      file2
      file3
   subfolder2
      file1

功能是:

def checkPath(self,folder):
        fileList=[]    
        try:
            directory=folder

            '''
             check if entered path exist 
             sleep for 2 seconds
            '''
            if os.path.exists(folder):
                print("{0} is a valid Path".format(folder))
                time.sleep(2)
                self.listWidgetPDFlist.clear()
                '''
                 looping over the path  using os,walk 
                ==> filter the PDF files then join the path entered with the fileName 
                ==> append the filtered files into a list  in order to apply list functions.
                '''
                for root,dirs,files in os.walk(directory):

                    for filename in files:
                        if filename.endswith(self.lineEdit_Ext.text()):

                            t=os.path.join(root,filename)

                            print(t)
                            fileList.append(t)

                # add the list into the  listWidgetPDFlist          
                self.listWidgetPDFlist.addItems(fileList)

                # get the total number of existing  PDF files in the requested path
                totalPDFNum=len(fileList)

                '''
                check if the length of the list if <= 0 
                yes ==> no PDF files were founded  TOTAL = 0 
                no ==>  PDF files were founded  TOTAL = totalPDFNum
                '''
                if(totalPDFNum <= 0 ):
                    print("{0} path doesn't includes any {1} files ".format(directory,self.lineEdit_Ext.text()))
                    self.lineEditTotalPDFnumber.setText(str(totalPDFNum))

                else:    
                    self.lineEditTotalPDFnumber.setText(str(totalPDFNum))
                    print ("\nthe ToTal Number of files  = {0} ".format(totalPDFNum) )        
                return folder

            #if entered path doesn't exist      
            else:    
                print("{0}is not a valid Path".format(folder))
                return False

        except Exception as e:
            print("this error occure {0}".format(e))
4

2 回答 2

1

此方法将递归构建树视图。

def make_tree(self, folder):  # folder here is a path to a folder
    root = self.populate(folder)
    self.tree_view.insertTopLevelItem(0, root)

def populate(self, path):
    tree_item = QTreeWidgetItem()
    tree_item.setText(0, os.path.basename(path))
    for file in os.listdir(path):
        if os.path.isdir(os.path.join(path, file)):
            tree_item.addChild(self.populate(os.path.join(path, file)))
        else:
            sub_item = QTreeWidgetItem()
            sub_item .setText(0, file)
            tree_item.addChild(sub_item )
    return tree_item

make_tree方法生成根目录对象并将其设置为树的顶级对象。

populate方法通过在提供的路径之外创建树项来递归地构建文件夹层次结构,然后如果该路径是目录,则将每个子项添加为新树项的子项。

请注意您将哪个文件夹设置为此方法的根目录,您最终可能会得到数千个树项目。实现某种深度限制将是一个很好的设计理念。

于 2018-03-29T13:45:34.457 回答
0

我认为你需要的pathlib.Path.glob比 os.walk 更容易实现,与 Path.parts 一起,你可以像这样组装一个嵌套的 dict:

from collections import defaultdict
from pathlib import Path
nested_dict = lambda: defaultdict(nested_dict)

def place_in_nested_dict(nested, place, value):
    if isinstance(place, str):
        place = [place]
    place = list(place)
    last = place.pop()
    for node in reversed(place):
        nested = nested[node]
    nested[last] = value

def find_files(root=Path('.'), pattern='**/*.pdf'):
    tree = nested_dict()
    for file in root.glob(pattern):
        if file.is_dir():
            continue
        parts = file.relative_to(root).parts
        name = file.name
        place_in_nested_dict(tree, parts, file.relative_to(root))
    return tree

使用这棵树来填充你的 TreeWidget,如下所示:

def populate(tree: dict, root: Path):
    tree_item = QTreeWidgetItem()
    tree_item.setText(0, str(root))
    for key, value in tree:
        if isinstance(value, dict):
            tree_item.addChild(populate(tree, key))
        else:
            tree_item.addChild(key)
    return tree_item
于 2018-03-29T14:08:28.920 回答