Scan CSV file and saving it into an array
Dave Angel
davea at davea.name
Wed Apr 24 20:01:13 EDT 2013
On 04/24/2013 07:01 PM, Ana DionĂsio wrote:
> Hello!
>
> I have this script that scans a csv file and if the value in the first column == 200 it saves that row into an array.
No it doesn't. It creates a list, then overwrites it with a numpy array,
then overwrites that with a list of strings representing one row.
If you want to really use a Python array, then read here:
http://docs.python.org/2/library/array.html
It'd probably be best to start with a precise problem statement,
presumably copied from your textbook or assignment sheet. What python
version is this for? And what OS? (that affects whether you need a
file mode) Exactly what data structure are you trying to build? What
type of a csv file are you trying to use? Is there a standard header
line? How big might the file be? What behavior do you want if there's
no line that begins with the field "200"? Or if there's more than one
such line? Or if there are less than 10 lines following it in the file?
What about a field of "0200"?
>
> The problem is, I need to save that row and the next 10 rows in that same array. What can I add to the script so it does that? I tried to do for row in len(10): but I get an error.
>
When you say "get an error" it could be one of many things. In this
case, it's obvious, since len() doesn't make sense with an integer
parameter. But in general you want to say either:
1) it gave me the wrong result. I expected AAAA and got BBBB
2) it did nothing at all.
3) it gave an exception, and here's the full traceback.
>
> p = csv.reader(open('file.csv'), delimiter=';')
> a=[0]*2881
> a = numpy.array(a, dtype=dict)
These two lines do nothing useful, and they confuse the reader of the
code, since they imply that the list will end up of size 2881, and/or as
a numpy array.
> for row in p:
> if row[0]=="200":
> a=row
> break
missing else clause. How do you detect that there was no match?
> print a
>
--
DaveA
More information about the Python-list
mailing list