Can Python print only selected fields from SQLite table to a file

时间:2016-08-31 17:55:34

标签: python sqlite io

Please forgive me if my terminology is not right. I have this:

CREATE TABLE table1 (field1 TEXT, field2 TEXT, field3 TEXT);

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

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()

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

SELECT field1 FROM table1 

in the sqlite shell and data is there.

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.

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.

Thanks!!

Edit: I think a variation on this might be what I'm looking for, yes?: https://stackoverflow.com/questions/10522830/how-to-export-sqlite-to-csv-in-python-without-being-formatted-as-a-listf

1 个答案:

答案 0 :(得分:1)

恕我直言,你没有在正确的物体上进行迭代。

for row in c.execute(sqlF1):
    e.write('%s\n' % row)

请参阅the docs中的示例。