user3291939
user3291939

Reputation: 39

Creating a number array out of a text file on python

I want to create an array of numbers out of every line of a text file, The file contains numbers as follow:

11
9
7
12

This is the code i have to open the file and append the numbers to the array:

f = open('randomNumberx.txt','r')
myList = []
for line in f:
    myList.append(line.strip())

the code above gives me the following:

['11', '9', '7', '12' ]

and id like to have it as:

[11,9,7, 12]

i am using this for a sorting algorithm and when i have the numbers with the '' it makes my algorithm fail and if i use the array of numbers it works fine. any ideas?

Upvotes: 0

Views: 1515

Answers (1)

msvalkon
msvalkon

Reputation: 12077

Try this:

with open('randomNumberx.txt','r') as f:
    mylist = [int(x) for x in f]

You can also use mylist = map(int, f) as commented by @falsetru.

You should learn to use the with -statement. It's useful for many situations in python. For files, it handles the opening and closing of the file so you won't have to.

Read this and this.

Upvotes: 2

Related Questions