python - 使用python向csv文件添加列标题,读取json

标签 python json csv

所以我有一个程序可以读取 json、压平它并转储 csv:

import json
import unicodecsv as csv
import sys
import glob
import os
from flatten_json import flatten_json

def createcolumnheadings(cols):
    #create column headings
    columns = cols.keys()
    columns = list( set( columns ) )
    return columns

doOnce=True

path=os.chdir(sys.argv[1])

for f in glob.glob("smallR.txt"):
    fName=os.path.splitext(f)[0]
    out_file= open( 'csv/' + fName+'.csv', 'wb' )
    csv_w = csv.writer( out_file, delimiter="\t", encoding='utf-8'  )

    with open(f, 'r') as handle:
        for line in handle:   
            data = json.loads(line)        
            flatdata =flatten_json(data)             
            if doOnce:
                columns=createcolumnheadings(flatdata) 
                columns.insert(0,'racism')
                csv_w.writerow( columns)                
                doOnce=False
            flatdata['racism']= 0
            csv_w.writerow(flatdata.get(x, u'') for x in columns)

这工作正常,但有一个问题。 我的程序只是从smallR.txt 的第一行获取列标题(加上它添加了“种族主义”列)。

后面的一些数据 (smallR.txt here ) 具有不同的列。这会导致输出不太正确,请参阅small.csv here .

是否有一种简单的方法可以使我的程序适应在后面几行中找到的新列标题?

最佳答案

在这种情况下,您需要首先扫描整个文件,以便获取所有可能的列:

with open(f, 'r') as handle:
    data = [json.loads(line) for line in handle]

columns = ['racism'] + list({k for entry in data for k in entry.keys()})

csv_w.writerow(columns)
for entry in entries:
    csv_w.writerow(entry.get(c, '') for c in columns)

加载内存中的所有数据。如果您不接受这一点,您可以读取该文件两次:一次获取列,另一次读取和写入:

with open(f, 'r') as handle:
    columns = ['racism'] + list({k for line in handle for k in json.load(line).keys()})
csv_w.write(columns)

with open(f, 'r') as handle:
    for line in handle:
        entry = json.loads(line)
        csv_w.write(entry.get(c, '') for c in columns)

缺少 flatten_json 函数定义,因此我只能猜测它的作用。

关于python - 使用python向csv文件添加列标题,读取json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40305924/

相关文章:

java - 无法将 CSV 值解析为 Double

javascript - 如何使用 D3.CSV 获取值

python - 如何在 Python 中将 INET 套接字连接到 PTY 设备

javascript - 如何在javascript中遍历json数组

java - 无法解析 JSON

Javascript/JSON 获取给定子节点的路径?

python - MySQL/Python -> 语句中占位符的语法错误?

python - 如何使用 beautiful soup 动态抓取内部链接

python - 格式 : wrong string width when UTF-8 encoding

javascript - AngularJS - 接收和下载 CSV