csv file read - every single character in one single list

孤街浪徒 提交于 2019-12-12 10:49:19

问题


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


回答1:


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.




回答2:


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'))


来源:https://stackoverflow.com/questions/41029964/csv-file-read-every-single-character-in-one-single-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!