Reputation: 797
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'))
?
Upvotes: 5
Views: 12991
Reputation: 501
You can typecast it to int, doing:
f = open('color.txt',"r")
g_colour_list=[]
for line in f:
g_colour_list.append(int(line.strip('\n')))
print (g_colour_list)
Upvotes: 0
Reputation: 1139
One possible solution is to cast the string to integer on appending. You can do it this way :
g_colour_list.append(int(line.strip('\n')))
If you think you will get floats as well then you should use float()
instead of int()
.
Upvotes: 1
Reputation: 8251
for line in f:
g_colour_list.append(int(line.strip('\n')))
You can parse a string s to int with int(s)
Upvotes: 0
Reputation: 1520
just cast your strings into integers:
g_colour_list.append(int(line.strip('\n')))
Upvotes: 2
Reputation: 66
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
Upvotes: 1