Stuck: Can't work out the error - index error python 3.5
<p>Here is part of my code (the part that is raising the issues):</p>

<pre><code>with open('list.txt') as csvfile:
    readCSV = csv.reader(csvfile, delimiter = ",") 
    GTINs = []
    products = []
    prices = [] 
    for row in readCSV: 
        GTIN = int(row[0])
        product = row[1]
        price = float(row[2])

        GTINs.append(GTIN) 
        products.append(product)
        prices.append(price)
</code></pre>

<p>On this line:</p>

<pre><code>GTIN = int(row[0])
</code></pre>

<p>I keep getting the error "IndexError: list index out of range", I have no idea how to fix it. Here is the information I am trying to extract (.txt file): </p>

<pre><code>69696961,Milk,1.29
55555555,Bread,0.49
45632549,Milkshake,1.99
</code></pre>

<p>The error occurred when I made an alteration to the the program (took away two lines).</p>

<p>Any help would be well appreciated as I am well and truly stuck.</p>

<p>It seems that you have an incorrect or black line in your csv. You can handle the index error with a try-except expression.</p>

<pre><code>try:
    GTIN = int(row[0])
    product = row[1]
    price = float(row[2])

    GTINs.append(GTIN) 
    products.append(product)
    prices.append(price)
except IndexError:
    # do something (like "pass" if you don't want that lines)
</code></pre>

<p>But if you are going to extract the columns you can use <code>itertools.zip_longest()</code></p>

<pre><code>from itertools import zip_longest
with open('list.txt') as csvfile:
    readCSV = csv.reader(csvfile, delimiter = ",")
    GTIN, product, price = zip_longest(*readCSV, fillvalue="")
</code></pre>

<p>Note: You can use anything else instead of an empty string for missed values. Or if you don't pass it to the function it will use the default value which is <code>None</code>.</p>

<p>As mentioned in comment if you want the items in their real type you can use following approach which is using a generator expression:</p>

<pre><code>from itertools import zip_longest
with open('list.txt') as csvfile:
    readCSV = csv.reader(csvfile, delimiter = ",")
    rows = ((int(a), b, float(c)) for a, b, c in csv.reader(csvfile))
    GTIN, product, price = zip_longest(*rows, fillvalue="")
</code></pre>

python python-3.x