将单词Null添加到CSV文件

时间:2017-11-13 09:04:16

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

我的查询抓取数据并将其放入CSV文件中。如下所示,我添加了一个映射,说明在写入CSV之前,是否有任何等于1970-01-01 00:00:00的字段将其置为空。

但是,当我进行此映射时,我遇到了错误。

我的代码:

from datetime import datetime
import csv



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


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

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']


mapping = {0: "None",1: "yes", 6: "no", 9: "maybe", 100:"no/yes", 101: "no/maybe"}
VT1 = my_dict['VT']
my_dict['VT'] = mapping.get(int(VT1), VT1)

mapping1 = {0: "New", 1: "Cancel", 2: "Future"}
DT1 = my_dict['DT']
my_dict['DT'] = mapping1.get(int(DT1), DT1)


mapping2 = {1920-01-01 00:00:00: 'Null'}
PT1 = my_dict['DATE']
my_dict['DATE'] = mapping2.get(int(PT1), PT1)


w.writerow(my_dict)

错误一:

mapping2 = {01/01/1970  00:00:00: ' '}
                  ^
SyntaxError: invalid token

错误二

Traceback (most recent call last):
  File "C:/Users/rich/.PyCharmCE2017.2/config/scratches/CSV.py", in <module>
    my_dict['DATE'] = mapping12.get(int(PT1), PT1)
ValueError: invalid literal for int() with base 10: '1920-01-01 00:00:00'

我怎么能说日期是否等于1920-01-01这个单词是否为空?

1 个答案:

答案 0 :(得分:1)

您的条目没有数据类型。

如果你正在处理字符串,那么它应该是一个字符串。

mapping2 = { "1920-01-01 00:00:00": "Null" }
PT1 = my_dict['DATE']
my_dict['DATE'] = mapping2.get( PT1, PT1 )