Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 没有数据时,代码无法运行_Python_Python 3.x_Csv_Dictionary_<img Src="//i.stack.imgur.com/RUiNP.png" Height="16" Width="18" Alt="" Class="sponsor Tag Img">elasticsearch - Fatal编程技术网 elasticsearch,Python,Python 3.x,Csv,Dictionary,elasticsearch" /> elasticsearch,Python,Python 3.x,Csv,Dictionary,elasticsearch" />

Python 没有数据时,代码无法运行

Python 没有数据时,代码无法运行,python,python-3.x,csv,dictionary,elasticsearch,Python,Python 3.x,Csv,Dictionary,elasticsearch,当我运行下面的查询时,如果[“VT”、“NCR”、“N”、“DT”、“RD”]等值中没有数据,则查询失败 错误信息为 ValueError: dict contains fields not in fieldnames: ‘VT’ 是否有一种方法可以确定是否有任何值中没有数据,并继续运行查询以获取python中有数据的值的数据? 例如:“TRY”、“CATCH”或“PASS”方法 我已经为此挣扎了好几天,有人能告诉我怎么做吗 我的代码: from datetime import datetim

当我运行下面的查询时,如果
[“VT”、“NCR”、“N”、“DT”、“RD”]等值中没有数据,
则查询失败

错误信息为

ValueError: dict contains fields not in fieldnames: ‘VT’
是否有一种方法可以确定是否有任何值中没有数据,并继续运行查询以获取python中有数据的值的数据?
例如:“TRY”、“CATCH”或“PASS”方法

我已经为此挣扎了好几天,有人能告诉我怎么做吗

我的代码:

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:
    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,) 
            header_present = True
             w.writerow(my_dict)

我想指出你评论中的一个缺陷

 # will write DATE, TIME, ... in correct place
 w.writerow(header_names,)
实际上,它在键的标题下写出字典的值。。。因此,您基本上要编写两个标题

关于错误,您可以忽略缺少的字段,并在它们不存在时设置默认值

可选的
restval
参数指定如果字典在
字段名中缺少键时要写入的值。如果传递给writerow()方法的字典包含字段名中未找到的键,则可选的
extrasaction
参数指示要采取的操作。如果将其设置为默认值“raise”,则会引发ValueError。如果设置为“忽略”,则忽略字典中的额外值

比如说

with open(csv_file, 'w', newline='') as f:
    # Open one csv for all the results 
    w = csv.DictWriter(f, fieldnames=header_names.keys(), restval='', extrasaction='ignore') 
    # There's only one header, don't need a boolean flag 
    w.writeheader()  
    # proceed to write results 
    for doc in res['hits']['hits']:
        my_dict = doc['_source']
        # Parse this dictionary however you need to write a valid CSV row 
        w.writerow(my_dict)

否则,不要使用DictWriter并自己形成CSV行。您可以使用
dict.get()
提取值,但设置数据中不存在的默认值

查找
dict.get()
您可以向我演示如何在代码中使用它吗?错误在哪里?请显示完整回溯您从未在此处分配名为
VT
DT
的变量。或者您缺少了一些代码@cricket-Traceback(最近一次调用最后一次):文件“C:/Users/Rich/.PyCharmCE2017.2/config/scratches/TRY.py”,第57行,在w.writerow(header_name,)#中将写入日期、时间等。。。在文件“C:\Users\Rich\AppData\Local\Programs\Python 36-32\lib\csv.py”的正确位置,第155行,在writerow中返回self.writer.writerow(self.\u dict\u to_list(rowdict))文件“C:\Users\Rich\AppData\Local\Programs\Python\Python 36-32\lib\csv.py”,第151行,在“dict\u to_list+”,”中。加入([repr(x)代表x在错误的_字段中))ValueError:dict包含字段名中不包含的字段:“VT”您能告诉我如何操作吗?老实说,我一直在苦苦挣扎到底该怎么办?我在这里给出了两个选择。。。我可能建议退一步,生成假数据,了解DictWriter的来龙去脉,并确定您是否真的需要它。我要指出的是,
w.writerow(header\u names,)
看起来没有必要,除非您确实想要“双”标题。从您的建议来看,dict.get()似乎很适合使用,因为您说过“您可以使用dict.get()提取值,但可以设置数据中不存在的默认值”,但我不确定如何使用dict.get()。除非您愿意向我展示如何将其与我的上述代码一起使用,否则我只是尝试了上面的代码,我在fieldnames=my_dict.keys上遇到了一个错误。我相信您可以在其他地方找到很多示例,但例如
vt=my_dict.get('vt',default vt')