user3605780 user3605780 - 1 year ago 55
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.


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()
rows = cursor.fetchall()
filename = '/logs/data.log'
fp = open(filename, 'w', newline='\n')
myFile = csv.writer(fp, lineterminator='\n')

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 Source

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='')

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


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download