2016-11-30 54 views
1

我想下載一些QListWidget中列出的圖像,我將鏈接傳遞給urllib,但它給了我TypeError:必須是字符串或緩衝區,而不是實例此錯誤。我試着在這裏查找,但無法找到任何解決方案,這裏是我的代碼。由於Python錯誤類型錯誤:必須是字符串或緩衝區,而不是實例

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() 
+0

請修復您的格式。你的縮進是關閉的,所以這段代碼實際上不會運行。 'imageFile'不需要關閉。使用'with'的重點在於,您不必管理這些資源。幷包括整個堆棧跟蹤。 – skrrgwasme

回答

1

很難肯定地說沒有看到堆棧跟蹤,但我懷疑這條線:

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

應改爲:

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

順便說一句,你不需要imageFile.close()行,因爲with語句會自動關閉該文件。

+0

是的兄弟你是對的。非常感謝它現在的工作:) – laslavinco

+0

哦好吧..我會刪除它:) – laslavinco

+0

嘿兄弟你能告訴我有什麼辦法在下載之前知道文件大小嗎? – laslavinco

相關問題