[Baypiggies] Preserving integers when loading a file into a list

Adam Hupp adam at hupp.org
Sun Jun 15 20:24:48 CEST 2008

You'll need a function that attempts integer conversion and returns
the original value if it fails:

def try_int_convert(sval):
        return int(sval)
    except ValueError:
        return sval

And then you can run the second column through that function:

result = []
for i in file(data_file,'rU'):
    splat = i.rstrip().split()
    result.append((splat[0], try_int_convert(splat[1])))

On Sun, Jun 15, 2008 at 11:09 AM, Al Nevarez <anevare2 at yahoo.com> wrote:
> Hello,
> What's the best way to preserve integers when loading a file into a list?
> for example.. assume we have a tab delimited file that looks like this:
> A       1
> B       2
> C       three
> I have a line in my program to read that file in like this:
> my_data=[line.strip().split('   ') for line in file(data_file,'rU')]
> the result in my_data is:
> [['A', '1'], ['B','2'], ['C','three']]
> But I need my_data to be like this:
> [['A', 1], ['B',2], ['C','three']]
> Needs to be automatic.. i.e. I'm not sure ahead of time, which if any value anywhere will be a string or an integer.
> Thanks!
> Al
> _______________________________________________
> Baypiggies mailing list
> Baypiggies at python.org
> To change your subscription options or unsubscribe:
> http://mail.python.org/mailman/listinfo/baypiggies

Adam Hupp | http://hupp.org/adam/

More information about the Baypiggies mailing list