Reputation: 39
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
[]
[]
[]
Upvotes: 3
Views: 477
Reputation: 5690
You read in the line fine and assign the first char of the line to the variable, but then you overwrite the variable with an empty list.
f=open("ballot.txt","r")
for line in f:
num1=line.strip().split(',')[0] # splits the line by commas and grabs 1st val
# ^^^^^^^^^^^^^^^^^^^^^^^^^^
print(num1)
This should do what you want. In your simple case, it's index 0, but you could index any value.
Since the file is comma-delimited, splitting the line by the comma will give you all the columns. Then you index the one you want. The strip()
call gets rid of the newline character (which would otherwise be hanging off the last column value).
As for the big picture, trying to get lists from each column, read in the whole file into a data structure. Then process the data structure to make your lists.
def get_column_data(data, index):
return [values[index] for values in data]
with open("ballot.txt", "r") as f:
data = f.read()
data_struct = []
for line in data.splitlines():
values = line.split(',')
data_struct.append(values)
print(data, '\nData Struct is ', data_struct)
print(get_column_data(data_struct, 0))
print(get_column_data(data_struct, 1))
The get_column_data
function parses the data structure and makes a list (via list comprehension) of the values of the proper column.
In the end, the data_struct is a list of lists, which can be accessed as a two-dimensional array if you wanted to do that.
Upvotes: 1
Reputation: 146
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)
Upvotes: 1