1
votes

I get this error even though my file has only two columns and I used them.

This is my code:

f_in = open('State_Deaths.csv', 'rt')
state_deaths = []
for line in f_in:
    line = line.strip()
    print(line)
    state, deaths = line.split(',')
    state_deaths += state, deaths
print(state_deaths)

This is a part of the file :

state, deaths
Wyoming,155
Mississippi,641
Arkansas,563
Montana,189
Alabama,862
Oklahoma,668
Kentucky,760
South Carolina,810
South Dakota,140
West Virginia,315
1
Could you show us a part of your file ? - Hamza Abbad
@HamzaAbbad I just added it - Saleh Alswiti
@SalehAlswiti Sure you don't have any lines with more than one comma in it? - jDo
Are you intending state_deaths to be a list of two-element tuples such as [(state1,deaths1), (state2,deaths2)], or a flat list such as [state1,deaths1,state2,deaths2]? - John Gordon
@jDo So should I edit the file ? - Saleh Alswiti

1 Answers

1
votes

I don't know if you're after a list of lists or a list of tuples, so here's both with some extra input checks that you might not need.

state_deaths_lists = []
state_deaths_tuples = []

with open('State_Deaths.csv', 'r') as f:
    for line in f:
        line = line.strip()
        if "," not in line:
            print("Error - No comma found")
        else:
            row_vals = line.split(",")
            if len(row_vals) != 2:
                print("Error - More than 2 elements in line/row")
            else:
                # all's in order
                state_deaths_lists.append(row_vals)
                state_deaths_tuples.append(tuple(row_vals))

If your input is nicely formatted and you want a list of list, just use this:

state_deaths = []

with open('State_Deaths.csv', 'r') as f:
    for line in f:
        line = line.strip()
        row_vals = line.split(",")
        state_deaths.append(row_vals)