1

my textfile has some numbers below

5
13
2
63

How can I store those numbers into an array? Thanks!!!

Kristine
  • 79
  • 1
  • 7
  • 1
    Did you try this yourself at all? This is something that can be very easily found in almost any Python tutorial. It's even in the main Python tutorial: https://docs.python.org/3/tutorial/inputoutput.html – idjaw Sep 04 '16 at 01:37
  • 2
    And searching for your question on stackoverflow leads to a lot of answers. [Here](http://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list-with-python) – idjaw Sep 04 '16 at 01:38
  • Thanks...I was looking for it, but I was lost somehow.. I think it's beacuse of my English.. thanks for your help! – Kristine Sep 04 '16 at 01:40

1 Answers1

1

This is one way to achieve that:

with open('filename') as file:
  lines = [i.strip() for i in file]

If you want your list to contain the numbers (int) instead of strings the following code will achieve this:

with open('seq.txt') as f:
  numbers = [int(i) for i in f]

Thanks to Ninja Puppy♦ to improve the code.

Jonas
  • 737
  • 1
  • 8
  • 20
  • 1
    Your answer is good, however, I would add this line `lines = [x.strip('\n') for x in lines]` at the end because otherwise each line in lines will contain a new line character. – Harrison Sep 04 '16 at 01:49
  • Thanks I'll update the answer to include that. – Jonas Sep 04 '16 at 01:53
  • No. Do not use `eval`. That is *very* [bad](http://stackoverflow.com/questions/1832940/is-using-eval-in-python-a-bad-practice) advice to give as a solution. Here is [another](http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html) – idjaw Sep 04 '16 at 01:56
  • Okay, I have change the code to use int( ) – Jonas Sep 04 '16 at 02:00
  • 2
    @Jonas `f.readlines()` returns a list - just iterate directly over `file` instead... – Jon Clements Sep 04 '16 at 02:05
  • Thanks @ninja, I've updated the code – Jonas Sep 04 '16 at 13:28
  • it says the variable "i" is not defined.. how can I define it? – Kristine Sep 17 '16 at 22:27
  • 'i' is defined in the list comprehension [... for i in ...]. Thus, it should be defined by the code provided. If you get an error, I would need to see your code to find the problem. – Jonas Sep 18 '16 at 06:42