Rich
Rich

Reputation: 177

How to add single quotes to strings in csv using Python

When the below query is executed, its grabs all the data I need however, is there a way to add single quotation marks to the column data called ‘PARTY’. So currently the data in the party column is being presented as 12105515480000. I would like the data to be presented in the CSV as ‘12105515480000’

Could someone show me how to fix this please?

My Code:

from datetime import datetime
from elasticsearch import Elasticsearch
import csv

es = Elasticsearch(["9200"])

res = es.search(index="search", body=
                {
                    "_source": ["VT","NCR","N","DT","RD"],
                    "query": {

                        "bool": {
                            "must": [{"range": {"VT": {
                                            "gte": "now/d",
                                            "lte": "now+1d/d"}}},

                                {"wildcard": {"user": "mike*"}}]}}},size=10)


csv_file = 'File_' + str(datetime.now().strftime('%Y_%m_%d - %H.%M.%S')) + '.csv'


header_names = { 'VT': 'Date',  'NCR': 'ExTime',  'N': 'Name', 'DT': 'Party', ' RD ': 'Period'}

with open(csv_file, 'w', newline='') as f:
    w = csv.DictWriter(f, fieldnames=header_names.keys(), restval='', extrasaction='ignore')
    w.writerow(header_names,)
    for doc in res['hits']['hits']:
        my_dict = doc['_source']

             w.writerow(my_dict)

CSV Output

Date      ExTime    Party
20171016    1       12105515480000
20171016    1       12105515480000
20171016    0       12105515480000

Ideal output

Date      ExTime    Party
20171016    1       ‘12105515480000’
20171016    1       ‘12105515480000’
20171016    0       ‘12105515480000’

Upvotes: 1

Views: 1042

Answers (1)

Felk
Felk

Reputation: 8224

The easiest way is to convert the actual data you want quoted to a string before writing to csv:

for doc in res['hits']['hits']:
    my_dict = doc['_source']
    my_dict['DT'] = str(my_dict['DT'])
    w.writerow(my_dict)

and also configure your csv writer to quote non-numeric chars with ' (not exactly the exact quote characters you used, but I figured that's not a requirement anyway):

w = csv.DictWriter(f, fieldnames=header_names.keys(), restval='', extrasaction='ignore',
                   quoting=csv.QUOTE_NONNUMERIC, quotechar="'")

Edit: since your data is already in textual form, this solution doesn't work for you. I don't know of any way to only put quotes around certain columns except manually doing it like so:

for doc in res['hits']['hits']:
    my_dict = doc['_source']
    my_dict['DT'] = "'" + my_dict['DT'].replace("'", r"\'") + "'"
    w.writerow(my_dict)

Upvotes: 1

Related Questions