2017-08-25 207 views
1

我試圖在Python中將url請求的結果轉換爲CSV reader object。輸出看起來不錯,但出現以下錯誤:Python:URL數據到csv閱讀器

for study_id, sample_id, run_id in reader: 
ValueError: not enough values to unpack (expected 3, got 1) 

首先,我請求數據,並將其轉換爲字符串數據:

req = urllib.request.Request(url=url_get_project_runs, headers={'Content-Type': 'text/plain'}) 
     res = urllib.request.urlopen(req) 
     dec_res = res.read().decode() 
     sys.stderr.write(str(dec_res)) --> for the print see below 
     return dec_res 

打印會給這樣的:

ERP001736,ERS494374,ERR598958 
ERP001736,ERS494394,ERR598963 
ERP001736,ERS494431,ERR598964 
ERP001736,ERS494445,ERR599170 
ERP001736,ERS494488,ERR598996 
ERP001736,ERS494518,ERR598976 
ERP001736,ERS494559,ERR598986 
ERP001736,ERS494579,ERR599078 
ERP001736,ERS494616,ERR598944 
ERP001736,ERS494628,ERR599001 
ERP001736,ERS488919,ERR1701760 

這對我來說似乎很好,因爲這些項目用逗號分開,「行」完好無損。 但是,如果我用這個作爲一個CSV閱讀器的輸入,並嘗試打印三列,如下:會發生

reader = csv.reader(dec_res, delimiter=',') 
     for study_id, sample_id, run_id in reader: 
      print(study_id + ", " + sample_id + ", " + run_id) 

以下錯誤: ValueError: not enough values to unpack (expected 3, got 1)

我還測試了一些代碼發現問題:

for row in reader: 
      sys.stderr.write(str(row)) 

這將給:

['E']['R']['P']['0']['0']['1']['7']['3']['6']['', '']['E']['R']['S']['4']['7']...etc 

回答

3

您正在將str傳遞給csv閱讀器,它需要一行一行地迭代。 str是逐個字符可迭代的。用StringIO或使用splitlines(或任何其他方法提供逐行迭代)來包裝您的字符串。

import csv 
from io import StringIO 

dec_res = """ERP001736,ERS494374,ERR598958 
ERP001736,ERS494394,ERR598963 
ERP001736,ERS494431,ERR598964 
ERP001736,ERS494445,ERR599170 
ERP001736,ERS494488,ERR598996 
ERP001736,ERS494518,ERR598976 
ERP001736,ERS494559,ERR598986 
ERP001736,ERS494579,ERR599078 
ERP001736,ERS494616,ERR598944 
ERP001736,ERS494628,ERR599001 
ERP001736,ERS488919,ERR1701760""" 

reader = csv.reader(StringIO(dec_res), delimiter=',') 
#reader = csv.reader(dec_res.splitlines(), delimiter=',') 

for study_id, sample_id, run_id in reader: 
    print(study_id + ", " + sample_id + ", " + run_id) 
+1

謝謝這麼多! – CodeNoob

+0

其實CSV可以(不總是)正常讀取的字符串,如果你通過他們的列表中: ' >>>數據= csv.reader([ 'ERP001736,ERS494374,ERR598958']) >>>名單(數據) [['ERP001736','ERS494374','ERR598958']] ' 但@damians的方式要好得多。 –