Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read numbers in text file as numbers in to list?

Tags:

I have a text file in which there are numbers in each line(only numbers). My color.txt looks like:

3
3
5
1
5
1
5

When I read this to list using

f=open('D:\\Emmanu\\project-data\\color.txt',"r")
    for line in f:
        g_colour_list.append(line.strip('\n'))
    print g_colour_list

the output is like

['3', '3', '5', '1', '5', '1', '5']

But I want it as:

[3,3,5,1,5,1,5]

How can I do that in the single line that is
g_colour_list.append(line.strip('\n'))?

like image 456
Emmanu Avatar asked Apr 23 '16 12:04

Emmanu


2 Answers

just cast your strings into integers:

g_colour_list.append(int(line.strip('\n')))
like image 143
mvelay Avatar answered Oct 13 '22 12:10

mvelay


Wrap a call to python's int function which converts a digit string to a number around your line.strip() call:

f=open('D:\\Emmanu\\project-data\\color.txt',"r")
    for line in f:
        g_colour_list.append(int(line.strip('\n')))
    print g_colour_list
like image 33
Dion Bridger Avatar answered Oct 13 '22 12:10

Dion Bridger