Output table from SQL into csv format and add quotation marks around a column

673 Views Asked by At

I am want to output a table from SQL as csv but I want to add quotation marks around the last column.

The name of the table I have in SQL is dbo.temp_table:

enter image description here

The output I want is a csv file, that when opened in notepad, the last column has double quotes:

enter image description here

When I use the below python code:

import pandas as pd
import numpy as np
import pyodbc
import pandas as pd 
import xlsxwriter
import csv


sql_conn = pyodbc.connect('DRIVER={DRIVER NAME}; SERVER=DATABASE_NAME; DATABASE=MY_DATABASE; Trusted_Connection=yes') 

query = "select * from dbo.temp_table"     
                                       
df = pd.read_sql(query, sql_conn)


file_out = 'C:\\Desktop\\TestFolder\\TestFile.csv'

df.to_csv(file_out, index = False, header=True)

I get this output (when the csv is opened in notepad):

enter image description here

I have also tried adding the quotation marks in the actual query in the python code:

import pandas as pd
import numpy as np
import pyodbc
import pandas as pd 
import xlsxwriter
import csv


sql_conn = pyodbc.connect('DRIVER={DRIVER NAME}; SERVER=DATABASE_NAME; DATABASE=MY_DATABASE; Trusted_Connection=yes') 

query = """select [name]
        ,'"' + [code] + '"' AS [code]
        from dbo.temp_table    """  
                                       
df = pd.read_sql(query, sql_conn)


file_out = 'C:\\Desktop\\TestFolder\\TestFile.csv'

df.to_csv(file_out, index = False, header=True)

but the output I get has 3 double quotes in the last column:

enter image description here

I think a solution could be to actually add the quotation marks within the python code but none of the questions I have looked at online seem to answer my question. I'd really appreciate some help.

0

There are 0 best solutions below