[Tutor] Reading Input Data
Kent Johnson
kent37 at tds.net
Tue Jan 15 21:44:16 CET 2008
lechtlr wrote:
> I want to read an input file (file.csv) that has two columns. I want to
> read 2nd column and assign variables that are strings and floats.
> Currently, I use the following split() function to read from the input
> file and create a list, and then assign each element to a variable.
>
> I am wondering there is any other easier (and elegant) way of doing this ?
Hmm. Are the strings and floats in a repeating pattern, or randomly
sprinkled around, or what?
Assigning a bunch of variables like this may not be the best way to
handle the data. Perhaps you could just keep them in a list?
Why are you doing this? How many lines are in the data file?
> data = []
> for line in open("file.csv"):
> columns = line.split(',')
> data.append([columns[1]])
This could be
data.append(columns[1])
there is no need to make a nested list.
>
> This script returns, say:
> data = [ ['20.0'], ['0.34'], ................,[ 'a:0.20, b:0.30, c:0.50' ]]
>
> Then, I assign to a set of variables, say:
>
> x1 = float(data[0][0]) ; x2 = float(data[1][0]);.............;xn =
> data[-1][0]
Without the extra nesting it would be
x1 = float(data[0]); etc.
Kent
>
>
> Thanks,
> Lex
>
>
>
>
>
>
> ------------------------------------------------------------------------
> Never miss a thing. Make Yahoo your homepage.
> <http://us.rd.yahoo.com/evt=51438/*http://www.yahoo.com/r/hs>
>
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list