[Baypiggies] Fw: Re: Preserving integers when loading a file into a list

Al Nevarez anevare2 at yahoo.com
Mon Jun 16 09:08:34 CEST 2008


Thanks for the tips everyone.
I'm running an older version of Python.. but the following combination of your suggestions worked just fine in yielding a list of lists with integers and strings preserved.

my_data[]
data_file='datasource.txt'

def try_int_convert(sval):
    try:
        return int(sval)
    except ValueError:
        return sval
        
for line in open(data_file):
       temp = [try_int_convert(x)  for x in line.strip().split('	')]  
       my_data.append(temp)


Works fine when the value is blank in the original tab delimited file too (must be a tab there of course).  Seems to work perfectly, but does anybody spot any issue?


Al



--- On Sun, 6/15/08, Brent Pedersen <bpederse at gmail.com> wrote:

> From: Brent Pedersen <bpederse at gmail.com>
> Subject: Re: [Baypiggies] Preserving integers when loading a file into a list
> To: "Jason Culverhouse" <jason at mischievous.org>
> Cc: baypiggies at python.org
> Date: Sunday, June 15, 2008, 1:46 PM
> On Sun, Jun 15, 2008 at 12:31 PM, Jason Culverhouse
> <jason at mischievous.org> wrote:
> > not x.isdigit() and x or int(x) is going to fail for
> empty string... ''
> >        not False and '' or int('')
> <-value error since
> >
> > You could combine Adam's try_int_convert
> >
> > import csv
> > import functools
> > import sys
> >
> > i = functools.partial(map, try_int_convert) # maybe 
> convert a list to int
> > t = functools.partial(tuple) # convert to tuple, not
> sure if you need the in
> > tuples
> >
> > #Read a TSV file from stdin and convert
> > [t(i(line)) for line in csv.reader(sys.stdin,
> dialect='excel-tab')]
> >
> > Jason
> 
> good point. out of curiosity, how is t =
> functools.partial(tuple),
> then using t() different from using tuple() directly?
> _______________________________________________
> Baypiggies mailing list
> Baypiggies at python.org
> To change your subscription options or unsubscribe:
> http://mail.python.org/mailman/listinfo/baypiggies


      


More information about the Baypiggies mailing list