【问题标题】:Python csv conversionPython csv 转换
【发布时间】:2017-01-26 21:14:10
【问题描述】:

我有下面的代码来遍历我的 CSV 值。输入数据(Sample.csv):

name,city
jack,nj
matt,ny

并以 JSON 格式创建输出。所需输出

[
{"name": "jack","city": "PA"},
{"name": "matt","city": "CA"}
]

代码输出:

[{"name,city": "jack,PA"};{"name,city": "matt,CA"};]

代码示例:

#!/usr/bin/python

import json
import csv
csvfile = open('sample.csv', 'r')
jsonfile = open('sample.csv'.replace('.csv','.json'), 'w')

jsonfile.write('{\n[\n')
fieldnames = csvfile.readline().replace('\n','').split(';')
reader = csv.DictReader(csvfile, fieldnames, delimiter=';')

from collections import OrderedDict
  for row in reader:  
    json.dump(OrderedDict([(f, row[f]) for f in fieldnames]), jsonfile, indent=4)
    jsonfile.write(';\n')
    jsonfile.write(']\n}')

最终输出未与键值对对齐。

【问题讨论】:

  • 仅供参考,如果 CSV 文件的第一行 字段名称,则无需直接处理 fieldnames。此外,还不清楚为什么要手动修改输出文件中的 JSON。另外,既然分隔符明明是,,那你为什么还要继续使用;?!
  • 我是 Python 新手,我尝试了其他示例,但这是将值附加到列表中,这在转换超过 1 GB 的文件时会花费大量时间。相反,我想附加到 json 输出文件而不是将其保存在内存中。这是让我更接近我需要的代码其他解决方案:stackoverflow.com/a/32158933/884808
  • 但是您在其中的每个项目之后都关闭了数组,并且在其中莫名其妙地使用了分号。如果您要手动编写 JSON,我建议您熟悉有效的语法。

标签: python json csv


【解决方案1】:

我能够实现我所需要的,可能不是最好的解决方案,但肯定是我现在正在寻找的。

import sys, getopt
ifile=''
ofile=''
format=''

#get argument list using sys module
myopts, args = getopt.getopt(sys.argv[1:],"i:o:f")

for o,a in myopts:
            if o == '-i':
                        ifile=a
            elif o == '-o':
                        ofile=a
            elif o == '-f':
                        format=a
            else:
                        print("Usage: %s -i input -o output -f format" % sys.argv[0])

#Reset the output file for each run
reset = open(ofile,"w+")
reset.close()

#Read CSV in a ordered Column Format & output in JSON format

from collections import OrderedDict
import csv
import json
import os
with open(ifile,'r') as f:
    reader = csv.reader(f,delimiter=',', quotechar='"')
    headerlist = next(reader)
    for row in reader:
            d = OrderedDict()
            for i, x in enumerate(row):
                    print x
                    d[headerlist[i]] = x
            with open(ofile,'a') as m:
               if format == "pretty":
                    m.write(json.dumps(d, sort_keys=False, indent=4, separators=(',', ': '),encoding="utf-8",ensure_ascii=False))
                    m.write(',\n')
               else:
                    m.write(json.dumps(d))
                    m.write(',\n')


#Module to remove the trailing delimiter

file = open(ofile, "r+")
file.seek(0, os.SEEK_END)
pos = file.tell() - 1
while pos > 0 and file.read(1) != ",":
     pos -= 1
     file.seek(pos, os.SEEK_SET)


if pos > 0:
     file.seek(pos, os.SEEK_SET)
     file.truncate()
file.writelines('\n')
file.close()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-19
    • 2015-08-07
    • 2018-09-20
    • 2013-07-15
    • 2018-01-25
    • 2011-04-23
    • 2016-11-30
    相关资源
    最近更新 更多