0

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

Community
  • 1
  • 1
Arkham Angel
  • 309
  • 1
  • 5
  • 18

1 Answers1

1

IMHO you are not iterating on the correct object.

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

See the examples in the docs.

turdus-merula
  • 8,546
  • 8
  • 38
  • 50
  • That works. But when I add more columns/fields like this: SELECT field1, field3, FROM table1 I get an error "TypeError: not all arguments converted during string formatting" and nothing piped to the file. – Arkham Angel Aug 31 '16 at 19:44
  • f.write("%s %s\n" % row) when you write two columns and so on. The "row" variable is a Python tuple. – turdus-merula Aug 31 '16 at 19:51
  • That's brilliant, thanks! One of the fields is an integer. Example field1 text, field2 integer, field3 text. I wrote %s %d %s, %s\n but I got error %d format a number is required (there are numbers in the fields) – Arkham Angel Aug 31 '16 at 20:10
  • Try to simply print the row variable in the console, maybe it will help. Check the types of the elements in the tuple. E.g. print type(row[0]), type(row[1]). – turdus-merula Aug 31 '16 at 20:57
  • 1
    Thank you for all the help. – Arkham Angel Sep 02 '16 at 18:06