1

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
12
  • 1
    Could you show us a part of your file ? Commented Mar 8, 2016 at 21:08
  • @HamzaAbbad I just added it Commented Mar 8, 2016 at 21:24
  • @SalehAlswiti Sure you don't have any lines with more than one comma in it? Commented Mar 8, 2016 at 21:34
  • 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]? Commented Mar 8, 2016 at 21:39
  • @jDo So should I edit the file ? Commented Mar 8, 2016 at 21:40

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

3 Comments

+1 for using the list append method instead of +=. Although valid, that is just confusing for anything but a simple counter.
Yeah, exactly. It's odd that python even allows the use of += for lists. It also works for adding strings/characters to other strings but that's also bad practice and should be replaced by "".join(). Too flexible for its own good, the snake is :P
Oh wow. It took me way too long to get that. Hahaha. python == snake (but Python is not snake!)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.