laslavinco laslavinco - 10 days ago 5
Python Question

Python error TypeError: must be string or buffer, not instance

i am trying to download some images which are listed in QListWidget i am passing the links to the urllib but its giving me TypeError: must be string or buffer, not instance this error. I tried looking up here but couldn't find any solution here is my code. Thanks

def downloadStuff(self):
files = self.listWidget.selectedItems()
for filename in files:
filename = filename.text()
filename = str(filename)
print filename
xfilename = filename.split('/')[-1]
with open('D:/'+xfilename,'wb') as imageFile:
print filename
imageFile.write(urllib.urlopen(filename)).read()
imageFile.close()

Answer

It's hard to say for sure without seeing the stack trace, but I suspect this line:

imageFile.write(urllib.urlopen(filename)).read()

Should instead be:

imageFile.write(urllib.urlopen(filename).read())

Incidentally, you don't need the imageFile.close() line, because the with statement closes the file for you automatically.