0

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?

3
  • Use int: myList.append(int(line)) Commented Feb 10, 2014 at 7:58
  • Strings are compared lexicographically, so '2'> '100' is True, that's why sort returns unexpected output. Commented Feb 10, 2014 at 8:01
  • 2
    with open('randomNumberx.txt') as f: myList = map(int, f) Commented Feb 10, 2014 at 8:03

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Itearting a file object yields lines. readlines() is not necessary. It will load all lines at once.
I didn't downvote, but you don't need the strip call and no need to use f.readlines(), simply iterate over the file object.
strip() is not required. int() ignore spaces.
Pretty neat, this did it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.