如何使用Python在csv中为字符串添加单引号

时间:2017-10-19 14:39:54

标签: python python-3.x csv python-3.6

当执行以下查询时,它会抓取我需要的所有数据,但有没有办法将单引号添加到名为'PARTY'的列数据中。因此,目前派对列中的数据显示为 12105515480000 。我希望数据在CSV中显示为 ‘12105515480000’

有人可以告诉我如何解决这个问题吗?

我的代码:

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输出

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

理想输出

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

1 个答案:

答案 0 :(得分:1)

最简单的方法是在写入csv之前将您想要引用的实际数据转换为字符串:

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

并配置你的csv编写器引用带有'的非数字字符(不完全是你使用的确切引号字符,但我认为这不是一个要求):

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

修改,因为您的数据已经是文本格式,此解决方案对您无效。我不知道有什么方法只能在某些列周围加上引号,除非手动这样做:

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