6

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...

Totem
  • 6,563
  • 4
  • 32
  • 60

2 Answers2

10

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.

K. A. Buhr
  • 34,593
  • 2
  • 34
  • 60
  • 1
    That worked just perfectly fine! Thanks a lot!! But I still don't quite get it. I read through some python tutorials considering csv-file read and I think I didn't see anything like that (but maybe there was and I didn't get it). What makes my file different? – IamnotaRabbit Dec 08 '16 at 01:10
  • 1
    Nothing different about your file. `csv.reader` expects to get an iterator over lines -- if it's passed a file object or if it's passed a list of strings (one per line), it works fine. If it's passed a single string, then it tries to iterate over it, but iterating over a string iterates over the individual characters. In this case, `csv.reader` acts as if you've passed it a file with one character per line, and you get weird output. – K. A. Buhr Dec 08 '16 at 02:21
0

Depending on your file, I think using readLine() instead of read() should get you to what you want. For example:

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

instead of

csvFile = csv.reader(ftpstream.read().decode('latin-1'))
UnsignedByte
  • 735
  • 9
  • 27