Python CSV reader not reading CSV data as I expect

I am trying to read some CSV data into an array. Perhaps I will explain what I'm trying to do better in Python than in English:

>>> line = ImportFile.objects.all().reverse()[0].file.split("\n")[0]
>>> line
'"007147","John Smith","100 Farley Ln","","Berlin NH 03570","Berlin","NH",2450000,"John",24643203,3454,"E","",2345071,1201,"N",15465,"I",.00,20102456,945610,20247320,1245712,"0T",.00100000,"",.00,.00,780,"D","000",.00,0\r'
>>> s = cStringIO.StringIO()
>>> s
<cStringIO.StringO object at 0x9ab1960>
>>> s.write(line)
>>> r = csv.reader(s)
>>> r
<_csv.reader object at 0x9aa217c>
>>> [line for line in r]
[]

As you can see, CSV data starts in memory, not in a file. I would expect my reader to have some of this data, but it is not. What am I doing wrong?

+3
source share
2 answers

You are using StringIOincorrectly. Try

s = cStringIO.StringIO(line)
r = csv.reader(s)
next(r)
# "['007147', 'John Smith', '100 Farley Ln', '', 'Berlin NH 03570', 'Berlin', 'NH', '2450000', 'John', '24643203', '3454', 'E', '', '2345071', '1201', 'N', '15465', 'I', '.00', '20102456', '945610', '20247320', '1245712', '0T', '.00100000', '', '.00', '.00', '780', 'D', '000', '.00', '0']"

and the result should be what you expect.

. : StringIO . , write(). , read() . s.reset() s.seek(0) reset StringIO .

+5

s.seek(0) s.write(line). s .

0

Source: https://habr.com/ru/post/1789091/


All Articles