Как исправить эту ошибку builtins.TypeError: ожидаемый объект str, bytes или os.PathLike, а не builtin_function_or_method - PullRequest
0 голосов
/ 29 июня 2018

У меня есть код, который позволяет пользователю выбрать из нужной папки пути и отобразить в QlistWidget существующие файлы docx.

Проблема в том, что когда пользователь выбирает файл, система должна возвращать полный путь к файлу. Но вместо этого отображается ошибка ниже:

builtins.TypeError: ожидаемый объект str, bytes или os.PathLike, а не builtin_function_or_method

я знаю, что ошибка в FileListSelected функция в этой строке:

p = pathlib.Path(self.fullPath.index)

но не знаю как это исправить.

примеры, это результат печати CheckPath:

где это существующие файлы в каталоге Download .

  • checkpath Полный путь => C: \ Users \ test \ Downloads \ cv.docx
  • checkpath Отображаемый путь => Загрузки \ cv.docx

=========================================

  • checkpath Полный путь => C: \ Users \ test \ Downloads \ Volunteer Card.docx
  • checkpath Отображаемый путь => Загрузки \ Volunteer Card.docx

=========================================

  • checkpath Полный путь => C: \ Users \ test \ Downloads \ insta Маро \ followers.docx
  • checkpath Отображаемый путь => insta maro \ follow.docx

=========================================

  • checkpath Полный путь => C: \ Users \ тест \ Downloads \ PdfToText-мастер \ примеры \ text-
  • capture \ sample-report.doc checkpath Отображаемый путь => текст захвата \ выборки report.doc

код:

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import (QMimeData)
from PyQt5.QtWidgets import (QApplication, QCheckBox, QColorDialog, QDialog,
                             QErrorMessage, QFileDialog, QFontDialog, QFrame, QGridLayout,
                             QInputDialog, QLabel, QLineEdit, QMessageBox, QPushButton, QMenu,QListWidgetItem)

from PyQt5.QtWidgets import *
import pdfviewer
import pathlib
from pathlib import Path
import os
import re
from os import path

import docx


class pdfViewer(pdfviewer.Ui_PdfPreviewWindow):

    def __init__(self,PdfPreviewObj):
        pdfviewer.Ui_PdfPreviewWindow.__init__(self)

        self.PdfPreviewObj =PdfPreviewObj 
        self.setupUi(PdfPreviewObj)
        self.PdfPreviewObj.show()


        self.ExportButton.clicked.connect(self.openExport)        
        self.listWidgetPDFlist.clicked.connect(self.FileListSelected)



    def FileListSelected(self):             # Function to select the desired file from the list in the left pane


        p = pathlib.Path(self.fullPath.index)
        print("this is P==>{}".format(p))
        if self.listWidgetPDFlist.selectedItems():
            Item = p , "\\" , self.listWidgetPDFlist.selectedItems()[0].text()            
            print("this is the cuurent Item =={}".format(Item)) 
            print("===============================================")
            return Item

        else:
            print("<b>!!! NO SELECTED FILE !!!</b>\n")


    def setExistingDirectory(self):               # create a pop up fileDirectory Dialog Message  in order to select the desired folder.

        self.fileList=[]
        dialog = QDialog()
        options = QFileDialog.DontResolveSymlinks | QFileDialog.ShowDirsOnly 
        Folder = QFileDialog.getExistingDirectory(dialog, "Open Folder" ,options=options)
        return Folder

    def checkPath(self,folder):         # Funtion to check the given path for the wanted extension (Files)

    try:
        directory=folder

        whichChecked=""
        for root,dirs,files in os.walk(directory):

            for filename in files:
                if len(self.lineEdit_Ext.text())>0:
                    self.lineEdit_Ext.setStyleSheet("background-color:white")
                    self.lineEdit_Ext.setPlaceholderText("Enter The Filetype Extention Here")

                    if filename.endswith(self.lineEdit_Ext.text()):
                        fullPath=os.path.join(root,filename)
                        print(fullPath)
                        self.fileList.append(fullPath)

                elif self.rdBtn_docx.isChecked() and filename.endswith("docx") or filename.endswith("doc") :
                    self.fullPath=os.path.join(root,filename)

                    self.p = pathlib.Path(self.fullPath)
                    print("checkpath  Full Path=> {}".format(self.p))
                    oneDir = os.path.join(*self.p.parts[-2:])                    
                    print("checkpath  Displayed Path => {}".format(oneDir))
                    print("=========================================")
                    self.fileList.append(oneDir)                        
                    whichChecked="docx - doc Ext was Selected"

                if len(self.fileList) > 0:
                    self.lineEdit_Ext.setStyleSheet("bacground-color:white;")
                    self.lineEdit_Ext.setPlaceholderText("{0}".format(whichChecked))
                else:
                    self.lineEdit_Ext.setStyleSheet("background-color:Red")
                    self.lineEdit_Ext.setPlaceholderText("No Ext is Specified")                            


        self.ListFilesInViewer(self.fileList)           # add the list into the  listWidgetPDFlist 
        self.SelectAll.setEnabled(True)

        return folder

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

    def ListFilesInViewer(self,Files):              # Function to list all the files in the Left pane 
        for item1 in Files:
            item = QtWidgets.QListWidgetItem(item1)
            item.setCheckState(QtCore.Qt.Unchecked)
            self.listWidgetPDFlist.addItem(item)
            self.lineEditTotalPDFnumber.setText(str(self.listWidgetPDFlist.count()))        

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    PdfPreviewWindow = QtWidgets.QMainWindow()
    pdfViewerUi = pdfViewer(PdfPreviewWindow)
    PdfPreviewWindow.show()
    sys.exit(app.exec_())

pdfviewer.py

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'C:\Users\test\Documents\Python_Projects\tests_scripts\qt_creator\wse_stakckOverFlow\pdfviewer.ui'
#
# Created by: PyQt5 UI code generator 5.10.1
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_PdfPreviewWindow(object):
    def setupUi(self, PdfPreviewWindow):
        PdfPreviewWindow.setObjectName("PdfPreviewWindow")
        PdfPreviewWindow.resize(767, 502)
        PdfPreviewWindow.setStyleSheet("background-color: rgb(255, 255, 255);")
        self.centralwidget = QtWidgets.QWidget(PdfPreviewWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout_3 = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout_3.setObjectName("gridLayout_3")
        self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
        self.tabWidget.setMinimumSize(QtCore.QSize(749, 0))
        self.tabWidget.setStyleSheet("")
        self.tabWidget.setTabShape(QtWidgets.QTabWidget.Rounded)
        self.tabWidget.setTabsClosable(False)
        self.tabWidget.setTabBarAutoHide(False)
        self.tabWidget.setObjectName("tabWidget")
        self.tab = QtWidgets.QWidget()
        self.tab.setObjectName("tab")
        self.gridLayout_4 = QtWidgets.QGridLayout(self.tab)
        self.gridLayout_4.setObjectName("gridLayout_4")
        self.ExportButton = QtWidgets.QPushButton(self.tab)
        self.ExportButton.setText("")
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(":/export.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.ExportButton.setIcon(icon)
        self.ExportButton.setIconSize(QtCore.QSize(40, 40))
        self.ExportButton.setFlat(True)
        self.ExportButton.setObjectName("ExportButton")
        self.gridLayout_4.addWidget(self.ExportButton, 2, 2, 1, 3)
        self.groupBoxPDFlist = QtWidgets.QGroupBox(self.tab)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.groupBoxPDFlist.setFont(font)
        self.groupBoxPDFlist.setAlignment(QtCore.Qt.AlignCenter)
        self.groupBoxPDFlist.setObjectName("groupBoxPDFlist")
        self.gridLayout = QtWidgets.QGridLayout(self.groupBoxPDFlist)
        self.gridLayout.setObjectName("gridLayout")
        self.SelectAll = QtWidgets.QPushButton(self.groupBoxPDFlist)
        self.SelectAll.setEnabled(True)
        self.SelectAll.setMinimumSize(QtCore.QSize(0, 0))
        self.SelectAll.setText("")
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap(":/checkBox.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.SelectAll.setIcon(icon1)
        self.SelectAll.setIconSize(QtCore.QSize(40, 40))
        self.SelectAll.setDefault(False)
        self.SelectAll.setFlat(True)
        self.SelectAll.setObjectName("SelectAll")
        self.gridLayout.addWidget(self.SelectAll, 0, 0, 1, 1)
        spacerItem = QtWidgets.QSpacerItem(89, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.gridLayout.addItem(spacerItem, 0, 1, 1, 1)
        self.listWidgetPDFlist = QtWidgets.QListWidget(self.groupBoxPDFlist)
        self.listWidgetPDFlist.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.listWidgetPDFlist.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
        self.listWidgetPDFlist.setObjectName("listWidgetPDFlist")
        self.gridLayout.addWidget(self.listWidgetPDFlist, 2, 0, 1, 2)
        self.gridLayout_4.addWidget(self.groupBoxPDFlist, 1, 0, 1, 4)
        self.groupBox_2 = QtWidgets.QGroupBox(self.tab)
        font = QtGui.QFont()
        font.setPointSize(13)
        font.setBold(False)
        font.setWeight(50)
        self.groupBox_2.setFont(font)
        self.groupBox_2.setStyleSheet("")
        self.groupBox_2.setAlignment(QtCore.Qt.AlignCenter)
        self.groupBox_2.setObjectName("groupBox_2")
        self.formLayout = QtWidgets.QFormLayout(self.groupBox_2)
        self.formLayout.setObjectName("formLayout")
        self.horizontalLayout_5 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_5.setObjectName("horizontalLayout_5")
        self.horizontalLayout_7 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_7.setObjectName("horizontalLayout_7")
        self.pushButtonOpenFolder = QtWidgets.QPushButton(self.groupBox_2)
        palette = QtGui.QPalette()
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Midlight, brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Midlight, brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Midlight, brush)
        brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
        self.pushButtonOpenFolder.setPalette(palette)
        font = QtGui.QFont()
        font.setPointSize(8)
        font.setBold(False)
        font.setItalic(False)
        font.setUnderline(True)
        font.setWeight(50)
        self.pushButtonOpenFolder.setFont(font)
        self.pushButtonOpenFolder.setMouseTracking(False)
        self.pushButtonOpenFolder.setAutoFillBackground(False)
        self.pushButtonOpenFolder.setText("")
        icon2 = QtGui.QIcon()
        icon2.addPixmap(QtGui.QPixmap(":/Open.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.pushButtonOpenFolder.setIcon(icon2)
        self.pushButtonOpenFolder.setIconSize(QtCore.QSize(36, 36))
        self.pushButtonOpenFolder.setCheckable(False)
        self.pushButtonOpenFolder.setAutoDefault(False)
        self.pushButtonOpenFolder.setDefault(False)
        self.pushButtonOpenFolder.setFlat(True)
        self.pushButtonOpenFolder.setObjectName("pushButtonOpenFolder")
        self.horizontalLayout_7.addWidget(self.pushButtonOpenFolder)
        self.verticalLayout_3 = QtWidgets.QVBoxLayout()
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.horizontalLayout_6 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_6.setObjectName("horizontalLayout_6")
        self.rdBtn_docx = QtWidgets.QRadioButton(self.groupBox_2)
        self.rdBtn_docx.setText("")
        icon3 = QtGui.QIcon()
        icon3.addPixmap(QtGui.QPixmap(":/File Format Doc-507x507"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.rdBtn_docx.setIcon(icon3)
        self.rdBtn_docx.setIconSize(QtCore.QSize(30, 30))
        self.rdBtn_docx.setObjectName("rdBtn_docx")
        self.horizontalLayout_6.addWidget(self.rdBtn_docx)
        self.verticalLayout_3.addLayout(self.horizontalLayout_6)
        self.lineEdit_Ext = QtWidgets.QLineEdit(self.groupBox_2)
        font = QtGui.QFont()
        font.setPointSize(10)
        self.lineEdit_Ext.setFont(font)
        self.lineEdit_Ext.setObjectName("lineEdit_Ext")
        self.verticalLayout_3.addWidget(self.lineEdit_Ext)
        self.horizontalLayout_7.addLayout(self.verticalLayout_3)
        self.horizontalLayout_5.addLayout(self.horizontalLayout_7)
        spacerItem1 = QtWidgets.QSpacerItem(158, 18, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_5.addItem(spacerItem1)
        self.formLayout.setLayout(0, QtWidgets.QFormLayout.SpanningRole, self.horizontalLayout_5)
        self.gridLayout_4.addWidget(self.groupBox_2, 0, 0, 1, 6)
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem2)
        self.lineEditTotalPDFnumber = QtWidgets.QLineEdit(self.tab)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.lineEditTotalPDFnumber.setFont(font)
        self.lineEditTotalPDFnumber.setObjectName("lineEditTotalPDFnumber")
        self.horizontalLayout.addWidget(self.lineEditTotalPDFnumber)
        self.labelTotalPDFnumber = QtWidgets.QLabel(self.tab)
        self.labelTotalPDFnumber.setObjectName("labelTotalPDFnumber")
        self.horizontalLayout.addWidget(self.labelTotalPDFnumber)
        self.gridLayout_4.addLayout(self.horizontalLayout, 2, 0, 1, 2)
        spacerItem3 = QtWidgets.QSpacerItem(502, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.gridLayout_4.addItem(spacerItem3, 2, 5, 1, 1)
        self.tabWidget.addTab(self.tab, "")
        self.gridLayout_3.addWidget(self.tabWidget, 0, 1, 1, 1)
        PdfPreviewWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(PdfPreviewWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 767, 21))
        self.menubar.setObjectName("menubar")
        PdfPreviewWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(PdfPreviewWindow)
        self.statusbar.setObjectName("statusbar")
        PdfPreviewWindow.setStatusBar(self.statusbar)

        self.retranslateUi(PdfPreviewWindow)
        self.tabWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(PdfPreviewWindow)

    def retranslateUi(self, PdfPreviewWindow):
        _translate = QtCore.QCoreApplication.translate
        PdfPreviewWindow.setWindowTitle(_translate("PdfPreviewWindow", "فرع التحليل - محرّك البحث "))
        self.ExportButton.setToolTip(_translate("PdfPreviewWindow", "<html><head/><body><p align=\"right\"><span style=\" font-size:12pt;\">نسخ</span></p></body></html>"))
        self.groupBoxPDFlist.setTitle(_translate("PdfPreviewWindow", "Files List"))
        self.SelectAll.setToolTip(_translate("PdfPreviewWindow", "<html><head/><body><p><span style=\" font-size:12pt;\">Check All Items</span></p></body></html>"))
        self.groupBox_2.setTitle(_translate("PdfPreviewWindow", "Search Panel"))
        self.pushButtonOpenFolder.setToolTip(_translate("PdfPreviewWindow", "<html><head/><body><p><span style=\" font-size:12pt;\">فتح مجلّد</span></p></body></html>"))
        self.lineEdit_Ext.setPlaceholderText(_translate("PdfPreviewWindow", "Enter The FileType Extention Here"))
        self.labelTotalPDFnumber.setText(_translate("PdfPreviewWindow", "Total"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("PdfPreviewWindow", "البرنامج"))

import resources_rc

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    PdfPreviewWindow = QtWidgets.QMainWindow()
    ui = Ui_PdfPreviewWindow()
    ui.setupUi(PdfPreviewWindow)
    PdfPreviewWindow.show()
    sys.exit(app.exec_())

Ответы [ 2 ]

0 голосов
/ 29 июня 2018

Похоже, что self.fullPath уже является строкой, так как вы делаете:

self.fullPath=os.path.join(root,filename)

, который возвращает строку.

Итак, когда вы делаете self.fullPath.index, вы вызываете индексный атрибут str, который является встроенной функцией, то есть builtins.TypeError: expected str, bytes or os.PathLike object, not builtin_function_or_method.

Моим лучшим предположением было бы проверить все вхождения self.fullPath, чтобы увидеть, всегда ли это объект, которым он должен быть.

0 голосов
/ 29 июня 2018

Проблема может заключаться в том, что вы возвращаете что-то в функцию "setExistingDirectory", а после этого запускаете elif вместо if. Таким образом, код после первой «Папки возврата» не должен быть достигнут. Если бы это было достигнуто, это бросило бы исключение.

Это означает, что fullPath никогда не оценивается.

def setExistingDirectory(self):               # create a pop up fileDirectory Dialog Message  in order to select the desired folder.

        self.fileList=[]
        dialog = QDialog()
        options = QFileDialog.DontResolveSymlinks | QFileDialog.ShowDirsOnly 
        Folder = QFileDialog.getExistingDirectory(dialog, "Open Folder" ,options=options)
        return Folder


                    elif self.rdBtn_docx.isChecked() and filename.endswith("docx") or filename.endswith("doc") :
                        self.fullPath=os.path.join(root,filename)
...