1

選択したディレクトリに存在するファイルのリストを表示する機能があり、ユーザーは検索された単語を入力します。プログラムはこれらのファイルをバックグラウンドで読み取って一致する単語を見つけ、最後に既存のリストを上書きして、一致する単語を含むファイル。

問題は 、システムがこのエラーを表示するwhile ループです。

while index < len(self.listWidgetPDFlist.count()):

builtins.TypeError: タイプ 'int' のオブジェクトには len() がありません

コード:

def listFiles(self):

        readedFileList = []
        index = 0
        while index < len(self.listWidgetPDFlist.count()):
            readedFileList.append(self.listWidgetPDFlist.item(index))
        print(readedFileList)

        try:
            for file in readedFileList:

                with open(file) as lstf:
                    filesReaded = lstf.read()
                    print(filesReaded)
                return(filesReaded)

        except Exception as e:
            print("the selected file is not readble because :  {0}".format(e))     
4

1 に答える 1

4

count()アイテムの数を返すため、整数になります。関数len() は、整数ではなく、イテラブルにのみ適用されるため、そのエラーが発生します。さらに、それは必要ありません。次のことを行う必要があります。

def listFiles(self):
    readedFileList = [self.listWidgetPDFlist.item(i).text() for i in range(self.listWidgetPDFlist.count())]
    try:
        for file in readedFileList:
            with open(file) as lstf:
                filesReaded = lstf.read()
                print(filesReaded)
                # return(filesReaded)

    except Exception as e:
        print("the selected file is not readble because :  {0}".format(e)) 

注: return を使用しないでください。最初の反復でループが終了します。

于 2018-04-04T08:19:24.557 に答える