Pellegrino
Pellegrino

Reputation: 29

From file to list

Hello guys what I am trying to do is to read a file with digits put like this example(below) to a list[1,2,3,4] :

1

2

3

4

5

Im doing this in class. I tried to do this without my class like this:

 def velocity():
 items = []
 with open('smhi.txt') as input:
     for line in input:
         items.extend(line.strip().split())
 return items         

When I print items I get ["1,","2","3","4"]

Upvotes: 1

Views: 57

Answers (2)

Kasravnd
Kasravnd

Reputation: 107357

you need to convert your numbers to int,and you can use a list comprehension as following but,note that as you define the list inside the function its in local name space so you couldn't access it outside of the function!so you need to return your list :

def velocity():
   with open('smhi.txt') as input:
       my_list=[int(line) for line in input if line.strip()]
   return my_list

result :

[1, 2, 3, 4, 5]

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174874

You need to explicitly convert the datatype of digits to integer.

with open('file') as f:
    print([int(i) for i in f if i.strip().isdigit()])

OR

with open('file') as f:
    print([int(j) for i in f for j in i.strip()])

OR

with open('file') as f:
    print([int(line) for line in f if line.strip()])

Upvotes: 0

Related Questions