Can Python print only selected fields from SQLite table to a file
<p>Please forgive me if my terminology is not right.  I have this:</p>

<pre><code>CREATE TABLE table1 (field1 TEXT, field2 TEXT, field3 TEXT);
</code></pre>

<p>I want to print only information from field1 and field3 for each row into a text file.  What I've tried is:</p>

<pre><code>e = open("export.txt", "w+")

sqlF1 = """
SELECT field1 FROM table1
"""
c.execute(sqlF1)
for row in e:
    #print c.fetchall
    e.write('%s\n' % row)

e.close()
</code></pre>

<p>The operation finishes without error but the text file is still empty.  I did a</p>

<pre><code>SELECT field1 FROM table1 
</code></pre>

<p>in the sqlite shell and data is there.</p>

<p>The end result is that I want to eventually have multiple fields piped to one line per row in a file.  I also want to put some text at the beginning and end of the values of each field I choose to pull this way.</p>

<p>Any advice or direction is helpful.  This operation doesn't have to be done with Python; I mean if I can figure out how to do it in conjunction with SQLite commands that would be OK too.</p>

<p>Thanks!!</p>

<p>Edit:  I think a variation on this might be what I'm looking for, yes?:  <a href="http://stackoverflow.com/questions/10522830/how-to-export-sqlite-to-csv-in-python-without-being-formatted-as-a-list/%22How%20to%20export%20sqlite%20to%20CSV%20in%20Python%20without%20being%20formatted%20as%20a%20list?%22">http://stackoverflow.com/questions/10522830/how-to-export-sqlite-to-csv-in-python-without-being-formatted-as-a-listf</a></p>

<p>IMHO you are not iterating on the correct object.</p>

<pre><code>for row in c.execute(sqlF1):
    e.write('%s\n' % row)
</code></pre>

<p>See the examples in <a href="https://docs.python.org/2/library/sqlite3.html" rel="nofollow">the docs</a>.</p>

python sqlite io