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