python - 将单词 Null 添加到 CSV 文件

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

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

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

我的代码:

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,我该如何判断输入“Null”一词?

最佳答案

您的条目没有数据类型。

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

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

关于python - 将单词 Null 添加到 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47260451/

相关文章:

python - 使检查的字符串数量根据一行中的字符串数量而变化

windows - 使用具有空值的命令按三列对 csv 文件进行排序?

file - 在 CSV 文件中传输二进制数据(图像等)

python - 删除 python pandas 中的 NaN 值

python - 椭圆曲线和点基数

python - pygame不刷新屏幕

python - While 循环语句 - 不同的答案

python - 如何使用元组值的自定义比较器创建字典的排序表示?

python - 如何将 mapinfo 文件加载到 geopandas 中

Python Click 命令无法识别选项