Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The way <code>csv.reader()</code> works is that it returns lists, each of which represents a <em>row</em>. So if you have a csv file that looks like this:</p> <pre><code>col1, col2, col3, col4 a, b, c, d e, f, g, h i, j, k, l </code></pre> <p>The corresponding contents of <code>csv.reader()</code> look like this:</p> <pre><code>&gt;&gt;&gt; with open('blah.csv', 'rb') as csv_file: ... cr = csv.reader(csv_file) ... for row in cr: ... print row ... ['col1', ' col2', ' col3', ' col4'] ['a', ' b', ' c', ' d'] ['e', ' f', ' g', ' h'] ['i', ' j', ' k', ' l'] </code></pre> <p>What's nice about lists is that you can slice them. </p> <pre><code>&gt;&gt;&gt; with open('blah.csv', 'rb') as csv_file: ... cr = csv.reader(csv_file) ... for row in cr: ... print row[0:3] ... ['col1', ' col2', ' col3'] ['a', ' b', ' c'] ['e', ' f', ' g'] ['i', ' j', ' k'] </code></pre> <p>That's the most obvious way to skip the last few columns of a csv table. You can also concatenate slices of lists:</p> <pre><code>&gt;&gt;&gt; with open('blah.csv', 'rb') as csv_file: ... cr = csv.reader(csv_file) ... for row in cr: ... print row[0:2] + row[3:] ... ['col1', ' col2', ' col4'] ['a', ' b', ' d'] ['e', ' f', ' h'] ['i', ' j', ' l'] </code></pre> <p>Putting it all together:</p> <pre><code>&gt;&gt;&gt; with open('blah.csv', 'rb') as csv_file: ... sql_insert = 'INSERT INTO table_name VALUES(?, ?, ?)' ... for row in csv.reader(csv_file): ... cu.execute(sql_insert, row[0:2] + row[3:]) ... &lt;sqlite3.Cursor object at 0x100535298&gt; &lt;sqlite3.Cursor object at 0x100535298&gt; &lt;sqlite3.Cursor object at 0x100535298&gt; &lt;sqlite3.Cursor object at 0x100535298&gt; &gt;&gt;&gt; cu.execute('SELECT * FROM table_name').fetchall() [(u'col1', u' col2', u' col4'), (u'a', u' b', u' d'), (u'e', u' f', u' h'), (u'i', u' j', u' l')] </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload