csv转存json,csvjson读写

Posted ychdzx

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csv转存json,csvjson读写相关的知识,希望对你有一定的参考价值。

csv 转存为json

import csv
import json

csvfile = open(‘test.csv‘, ‘r‘)
jsonfile = open(‘record.json‘, ‘w‘)

headers = [‘class‘, ‘name‘, ‘sex‘, ‘height‘, ‘year‘]
readers = csv.DictReader(csvfile, headers)

for row in readers:
    json.dump(row, jsonfile)
    jsonfile.write(‘
‘)

顺便整理一下csv、json和excel 的读写吧

csv 读写

用pandas

# 读
import pandas as pd

data = pd.read_csv(‘test.csv‘)
print(data)



# 写
import pandas as pd

a = [1, 2, 3]
b = [4, 5, 6]

dataFrame = pd.DataFrame({‘a_name‘: a, ‘b_name‘: b})
dataFrame.to_csv(‘test1.csv‘, index=True, mode=‘w‘, sep=‘ ‘)

用csv

# 读
import csv
with open("test.csv","r") as f:
    reader = csv.reader(f)
    #这里不需要readlines
    for line in reader:
        print line



# 写
import csv

headers = [‘class‘,‘name‘,‘sex‘,‘height‘,‘year‘]

rows = [
        [1,‘xiaoming‘,‘male‘,168,23],
        [1,‘xiaohong‘,‘female‘,162,22],
        [2,‘xiaozhang‘,‘female‘,163,21],
        [2,‘xiaoli‘,‘male‘,158,21]
    ]

with open(‘test.csv‘,‘w‘)as f:
    f_csv = csv.writer(f)
    f_csv.writerow(headers)
    f_csv.writerows(rows)

json 读写

dumps() 将一个python对象编码为json对象

loads() 讲一个json对象解析为python对象

dump() 将python对象写入文件

load()从文件中读取json数据

1、dumps()和loads()主要用于Python和json对象的相互转化。

import json

prices = {
    ‘ACME‘: 45.23,
    ‘AAPL‘: 612.78, 
    ‘IBM‘: 205.55,
    ‘HPQ‘: 37.20,
    ‘FB‘: 10.75
}

a= json.dumps(prices)    #编码为json
print(a)
‘‘‘
Out[40]: ‘{"ACME": 45.23, "AAPL": 612.78, "IBM": 205.55, "HPQ": 37.2, "FB": 10.75}‘
‘‘‘
b = json.loads(a)  #解码为python对象
print(b)
‘‘‘
Out[42]: {‘AAPL‘: 612.78, ‘ACME‘: 45.23, ‘FB‘: 10.75, ‘HPQ‘: 37.2, ‘IBM‘: 205.55}

2.dump()与load()主要用于读写json文件

写入json文件
import json



prices = {
    ‘ACME‘: 45.23,
    ‘AAPL‘: 612.78,
    ‘IBM‘: 205.55,
    ‘HPQ‘: 37.20,
    ‘FB‘: 10.75
}

with open(‘price.json‘, ‘w‘) as f:
    json.dump(prices,f)
此时在当前目录下生成prices.json文件。

内容如下:{"ACME": 45.23, "AAPL": 612.78, "IBM": 205.55, "HPQ": 37.2, "FB": 10.75}
读取json文件
import json
with open(‘price.json‘, ‘r‘) as f:
    a = json.load(f)    #此时a是一个字典对象


with open(‘record.json‘, ‘r‘) as ff:
for row in ff:
    a = json.loads(row)  ## json不止一行时

print(a)
print(type(a))

print(a[‘ACME‘]
‘‘‘
Out[47]: 45.23

参考:
python读写json文件 https://blog.csdn.net/goodxin_ie/article/details/89387333
python写入csv文件的几种方法总结 https://waple.blog.csdn.net/article/details/70049953?utm_source=app
【Python】JSON读取大量数据错误:JSONDecodeError: Extra data: line 2 column 1或者ValueError: Extra data: 类似错误处理
https://blog.csdn.net/ztf312/article/details/97817037





以上是关于csv转存json,csvjson读写的主要内容,如果未能解决你的问题,请参考以下文章

Python处理CSVJSON和XML数据的简便方法

Python处理CSVJSON和XML数据的简便方法

Python 处理CSVJSON和XML数据的简便方法

Spark---读取csvjson文件

如此美妙,Python 处理CSVJSON和XML数据的方法真简便

csv文件快速转存到mysql