0

Not able to get a line by line outputs after writing values into CSV file since one of the value contains a comma

Code snippet:

with open('queryout.csv', 'w') as f:
    f.write("%s\n" % header)
    for key in values:
        var_value = (str(key['count']) + "," + str(key['average']) + "," + str(key['example']))
        f.write("%s\n" % var_value)

Count and average variables contains integer and example variable contains query like select id,hdh,dhd from table name where column.

Because of example contains a comma I am not able to see them as expected like CSV format while printing.

Could you please anyone help me out?

Thanks in advance

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 3
    use the CSV module to wrap each field in qoute chars – Chris Doyle Nov 04 '19 at 09:05
  • Could you provide your sample dictionary? You'll have to check each `key['count'], key['average'], key['example']` for commas and if so, convert them to `"blah, blah"` – ycx Nov 04 '19 at 09:08
  • The duplicate mentions `csv` module, but specifically your example looks like it needs `csv.DictWriter` since values appears to be a list of dictionaries. – Mark Tolonen Nov 04 '19 at 09:43
  • {u'count': u'98', u'average': u'663.76', u'example': u"SELECT column1, column2 AS FROM cmdb cmdb0 WHERE filed>100"},{u'count': u29', u'average': u'663.76', u'example': u"SELECT column1, column7 FROM table WHERE filed>100"} – Mohankrishna Nov 04 '19 at 11:49

2 Answers2

0

Instead of using str(key['count']), you should write your own function.

def str_handler(string):
    if ',' in string:
        return '"' + str(string) + '"'
    else:
        return str(string)

Use it using str_handler(key['count']).

The concept here is that you will have to handle the edge case of your key field having a special character, in this case, its a ,.

ycx
  • 3,155
  • 3
  • 14
  • 26
-1

You may try use panda

import os 
import csv 
import numpy as np 
import pandas as pd

Output_file = pd.read_csv("queryout.csv") 
print(Output_file)


for x_m in range(0, len(['count'])):
    print(Output_file.loc[x_m,'count'])
    print(Output_file.iloc[x_m])
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jolin
  • 231
  • 3
  • 14