我有一个函数,显示所选目录中存在的文件列表,然后用户输入一个搜索单词,程序在后台读取这些文件,以便找到匹配的单词,最后它只显示包含匹配单词的文件,从而覆盖现有的列表。
问题是同时循环系统显示了这个错误:
而索引< 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)) 发布于 2018-04-04 08:19:24
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,您将在第一次迭代中完成循环。
https://stackoverflow.com/questions/49645898
复制相似问题