Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transferring numbers from a text file to an array

I have a text file that has three lines and would like the first number of each line stored in an array, the second in another, so on and so fourth. And for it to print the array out. The text file:

0,1,2,3,0
1,3,0,0,2
2,0,3,0,1

The code I'm using (I've only showed the first array for simplicity):

f=open("ballot.txt","r")
for line in f:
    num1=line[0]
    num1=[]
    print(num1)

I expect the result for it to print out the first number of each line:

0
1
2

the actual result i get is

[]
[]
[]
like image 586
Joe M Avatar asked Dec 10 '25 15:12

Joe M


1 Answers

It looks like you reset num1 right? Every time num1 is reseted to an empty list before printing it.

f=open("ballot.txt","r")
for line in f:
    num1=line[0]
    #num1=[] <-- remove this line
    print(num1)

This will return the first char of the line. If you want the first number (i.e. everything before the first coma), you can try this:

f=open("ballot.txt","r")
for line in f:
    num1=line.split(',')[0]
    print(num1)
like image 167
Tanphi Avatar answered Dec 13 '25 05:12

Tanphi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!