【发布时间】:2018-03-24 10:54:10
【问题描述】:
当我运行以下代码并创建 CSV 时。在我的 CSV 文件中有空白行。我想知道如何摆脱空白行。
例如。
第 1 行 - 将包含我需要的数据
第 2 行 - 将为空白
第 3 行 - 将包含我需要的数据
第 4 行 - 将为空白
第 5 行 - 将包含我需要的数据
等等
我希望 CSV 文件在创建时呈现出来
第 1 行 - 将包含我需要的数据
第 2 行将包含我需要的数据
第 3 行 - 将包含我需要的数据
等等
我的代码在下面
from elasticsearch import Elasticsearch
import csv
es = Elasticsearch(["9200"])
# Replace the following Query with your own Elastic Search Query
res = es.search(index="search", body=
{
"_source": ["DTDT", "TRDT", "SPLE", "RPLE"],
"query": {
"bool": {
"should": [
{"wildcard": {"CN": "TEST1"}}
]
}
}
}, size=10)
header_names = { 'DTDT': 'DATE', 'TRDT': 'TIME', ...}
with open('mycsvfile.csv', 'w') as f: # Just use 'w' mode in 3.x
header_present = False
for doc in res['hits']['hits']:
my_dict = doc['_source']
if not header_present:
w = csv.DictWriter(f, my_dict.keys())
w.writerow(header_names) # will write DATE, TIME, ... in correct place
header_present = True
w.writerow(my_dict)
有人能告诉我怎么去这个地方吗?整天卡在这上面。
谢谢
【问题讨论】:
-
您能否举例说明
res['hits']['hits']中的docs是什么样的? -
使用熊猫
df.dropna(how='all')pandas.pydata.org/pandas-docs/stable/generated/…
标签: python python-3.x python-3.5 python-3.4 python-3.6