Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

csv file read - every single character in one single list

I am rather new to python and could really need some help (I did not find anything that helped me by now).

I want to read a csv-file to a list, but unfortunately my output is not as expected. Instead of having a list like:

[[Weiz;61744],[Deutschlandsberg;5645]]

I have a list that looks like this:

[['W'],['e'],['i'], etc.]

My code looks like this:

def readCSV(file):
    for row in open(file,"r+"):
        ftpstream = urllib.request.urlopen(row)
        csvFile = csv.reader(ftpstream.read().decode('latin-1'))
        data = [row for row in csvFile]
        for row in data:
            print(row)

Can anybody please tell me why it is not working? I am really struggling right now...

like image 506
IamnotaRabbit Avatar asked Dec 08 '16 00:12

IamnotaRabbit


1 Answers

The function csv.reader expects to receive a list of lines, not a single string (such as would be returned by ftpstream.read().decode('latin-1')). If you replace:

csvFile = csv.reader(ftpstream.read().decode('latin-1'))

with

csvFile = csv.reader(ftpstream.read().decode('latin-1').split('\n'))

I believe it will work as you expect.

like image 152
K. A. Buhr Avatar answered Oct 16 '22 14:10

K. A. Buhr