user3605780 user3605780 - 21 days ago 5
MySQL Question

how can I write rows from mysql to logfile in python

How can I write the rows of a mysql select to a logfile so every row is on a newline and all columns are split by "|"?

I'm using python3.

EDIT:

I see I have given a bit to little info, sorry.

What I have is this:

query = 'SELECT * FROM `table1` where date < x'

cursor = db.cursor()
cursor.execute(query)
rows = cursor.fetchall()
filename = '/logs/data.log'
fp = open(filename, 'w', newline='\n')
myFile = csv.writer(fp, lineterminator='\n')
myFile.writerows(rows)


However this is comma seperated and it can happen that there are comma's in the datafields and all rows are appended after another instead of on a newline.

And would it be possible to directly tar the file which is created?

Answer

Here's a sketch of what I think you need:

import csv
rows = cursor.fetchall()
filename = '/logs/data.log'
fp = open(filename, 'w')  #  newline='\n' not needed

w = csv.writer(fp, lineterminator='\n', delimiter='|', quotechar='')
w.writerows(rows)

fetchall returns a list of tuples. The csv.writer documentation doesn't say, but I expect is takes any sequence of sequences.

HTH.