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

Brent Pedersen bpederse at gmail.com
Sun Jun 15 20:43:08 CEST 2008


hi, you can use the isdigit() method on a string.

$ cat stuff.txt
1 a 2
b b b
a 2 4
0 0 0


>>> for line in open('stuff.txt'):
...       [not x.isdigit() and x or int(x) for x in line.strip().split()]
[1, 'a', 2]
['b', 'b', 'b']
['a', 2, 4]
[0, 0, 0]




2 4 c

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
>


More information about the Baypiggies mailing list