我正在使用 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))