[Tutor] Help required

Mark Lawrence breamoreboy at yahoo.co.uk
Thu Apr 4 18:00:47 CEST 2013


First up please give a sensible subject, say "problem parsing csv file".

I'm assuming the crud shown below is due to you posting in html, please 
use plain text instead.

On 20/03/2013 06:12, Arijit Ukil wrote:
> I am new to python. My intention is to read the file digi.txt and store
> in separate arrays all the values of each columns. However, the
> following program prints only the last value, i.e. 1350696500.0.
> Please help to rectify this.
>
> f = open (/"digi.txt"/, /"r+"/)

You might like to use the with statement as it saves the explicit close 
later.  Do you really need update mode?  I'll assume not.

with open('digi.txt', 'r') as f:

>
> datafile = f.readlines()

datafile is a poor name, it's the contents of the file here not the file 
itself.

>
> list_of_lists = datafile

This gives another name for datafile which you only use in the for loop, 
you can use datafile directly.

> fordata inlist_of_lists:
>      lstval = data.split (/','/)

The csv module from the standard library can look after this for you.

>      timest = float(lstval[0])
>      energy = float(lstval[1])

You do nothing with timest and energy within the for loop.

>
> f.close()
> printtimest

You're printing the last value for timest here.

So you need something like the following, I'll leave you to look up the 
csv module if you're interested.

with open('digi.txt', 'r') as f:
     lines = f.readlines()
     timestamps = []
     energies = []
     for line in lines:
         splits = line.split(',') # I'll admit not the best name
         timestamps.append(float(splits[0]))
         energies.append(float(splits[1]))

     # process timestamps and energies to your heart's content

>
> Regards,
> Arijit Ukil

-- 
If you're using GoogleCrap™ please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence



More information about the Tutor mailing list