Python CSV writer缺少d行

2024-09-28 21:50:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我在将json数据转储到CSV文件时遇到了一个问题。CSV文件中通常会缺少一个json数据块,但是如果在控制台或文件中打印json,则可以看到该数据块。在

本质上,我调用一个服务两次,然后返回两个json响应,并将其解析并转储到CSV文件中。服务只能以7天的增量(unix时间)调用,因此我实现了在一段时间内调用该服务的逻辑。在

我使用的是python香草json和{}库。在

首先,创建带有标题的CSV:

with open ('history_' + datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")+'.csv', 'wb') as outcsv:
    writer = csv.writer(outcsv)
    writer.writerow(["Column1","Column2", "Column3", "Column4", "Column5",
              "Column6"])

然后,我有一个计数器,它调用服务两次,五十次(在打开CSV文件之后):

^{pr2}$

json响应示例:

{"Value": 
  [
    {"ExampleName": "Test", 
     "ExampleNameTwo": "Test2", 
     "ExampleDate": "1436103790", 
     "ExampleCode": 00000001, 
     "ExampleofExample": "abcd", 
     "AnotherExample": "hello"},
     {"ExampleName": "Test2", 
     "ExampleNameTwo": "Test3", 
     "ExampleDate": "1436103790", 
     "ExampleCode": 00000011, 
     "ExampleofExample": "abcd", 
     "AnotherExample": "hello2"},
  ]
}

CSV输出列如下所示:

ExampleName   ExampleNameTwo   ExampleDate   ExampleCode  ExampleofExample   AnotherExample

最后,CSV如下:

for item in jsonResponseOne['Value']:
                row = []
                row.append(str(item['ExampleName'].encode('utf-8')))
                if item.get("ExampleNameTwo"):
                    row.append(str(item["ExampleNameTwo"]))
                else:
                    row.append("None")
                row.append(str(item['ExampleDate']))
                row.append(str(item['ExampleCode'].encode('utf-8')))
                row.append(str(item['ExampleofExample'].encode('utf-8')))
                row.append(str(item['AnotherExample'].encode('utf-8')))
                writer.writerow(row)
for item in jsonResponseTwo['Value']:
                anotherRow= []
                anotherRow.append(str(item['ExampleName'].encode('utf-8')))
                if item.get("ExampleNameTwo"):
                    anotherRow.append(str(item["ExampleNameTwo"]))
                else:
                    anotherRow.append("None")
                anotherRow.append(str(item['ExampleDate']))
                anotherRow.append(str(item['ExampleCode'].encode('utf-8')))
                anotherRow.append(str(item['ExampleofExample'].encode('utf-8')))
                anotherRow.append(str(item['AnotherExample'].encode('utf-8')))
                writer.writerow(anotherRow)

为什么我的CSV输出会丢失一整行数据(来自JSON响应的一块数据)?在


Tags: 文件csv数据jsonitemutfencodewriter