I am a beginner with python and I am trying to print the results of a query to a pipe delimited file. How can I modify this script to do so?
import cx_Oracle
import csv
connection = cx_Oracle.connect("blah blah blah connection stuff")
cursor = connection.cursor()
cursor.execute("select column1, column2 from schema.table")
result=cursor.fetchall()
c = csv.writer(open("C:\mystuff\output.csv","wb"))
c.writerow(result)
Right now it prints out like this
“(10001965, ‘0828442C00548’)”,”(10001985, ‘0696230C35242’)”,”(10001986, ‘C41251’)”
I want it to print pipe delimited and a new line at the end of the row. Thanks for any help!
10001965|0828442C00548\n
10001985|0696230C35242\n
10001986|C41251\n
To get the pipes symbol as the delimiter, you can pass in a “delimiter” parameter when creating the writer:
c = csv.writer(open(“C:\mystuff\output.csv”,”wb”), delimiter=”|”)
you can also add a lineterminator param:
c = csv.writer(open(“C:\mystuff\output.csv”,”wb”), delimiter=”|”, lineterminator=”\n”)
though it is supposed to default to “\r\n”
I think you may also have a problem with the call to “writerow”. The db result is a list of tuples, to correctly write this to the csv files, you should use “writerows” (NOTE THE plural form of the function). This should correctly handle the list and put the pairs of db values on separate line, correctly delimited with pipes. Currently, your code is writing one “row”, that’s why there are no newlines separating the data values.
New code:
c = csv.writer(open(“C:\mystuff\output.csv”,”wb”), delimiter=”|”)
c.writerows(result)