2017-03-16 88 views
0

我想使用請求庫來讀取CSV文件,但我遇到了問題。使用URL給出錯誤的Python讀取CSV文件

import requests 
import csv 

url = 'https://storage.googleapis.com/sentiment-analysis-dataset/training_data.csv' 
r = requests.get(url) 
text = r.iter_lines() 
reader = csv.reader(text, delimiter=',') 

我又試圖

for row in reader: 
    print(row) 

,但它給了我這個錯誤:

Error: iterator should return strings, not bytes (did you open the file in text mode?) 

我應該如何解決這個問題?

回答

1

你可能想要的是:

text = r.iter_lines(decode_unicode=True) 

這將返回 - 迭代器的strings而不是bytes - 迭代器。 (有關文檔,請參見here)。

+0

它工作正常!非常感謝! –