2

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?

6
  • Can you post the code you wrote to attempt to solve this problem and describe what specifically is not working the way you expect or want? Commented Nov 15, 2016 at 22:11
  • What have you done so far? Have you queried the database and gotten the results? Have you looped over the results? Do you know about str.join()? Commented Nov 15, 2016 at 22:12
  • @takendarkk I edited my question, I do have good results from the query Commented Nov 15, 2016 at 22:24
  • @RocketHazmat I edited my question Commented Nov 15, 2016 at 22:24
  • 2
    Besides lineterminator, csv.writer has delimiter and quotechar. Does that do what you want? Commented Nov 15, 2016 at 22:30

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It gives an error with the empty quotechar but without quotechar it works. I viewed the file in notepad which didn't show the rows on a newline but in nano it does. thanks. Do you happen to know how I can tar it directly?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.