當執行下面的查詢時,它會抓取我需要的所有數據,但有沒有方法可以將單引號添加到名爲「PARTY」的列數據中。所以目前派對專欄中的數據顯示爲12105515480000
。我希望數據以CSV格式顯示爲‘12105515480000’
如何使用Python將單引號添加到csv中的字符串
有人可以告訴我如何解決此問題嗎?
我的代碼:
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’
看起來數據是數字。你想只將它作爲一個字符串寫入csv,或者首先從elasticsearch讀取它作爲字符串? – Felk
將它作爲字符串寫入CSV,所以當創建CSV文件時,我將在派對列「12105515480000」下看到。如果這是有道理的。你能告訴我如何做到這一點嗎? – Rich