码迷,mamicode.com
首页 > Web开发 > 详细

csv转存json,csv、json读写

时间:2020-07-08 13:27:31      阅读:68      评论:0      收藏:0      [点我收藏+]

标签:imp   err   load()   pen   error:   python   dataframe   sdn   解析   

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(‘\n‘)

顺便整理一下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,csv、json读写

标签:imp   err   load()   pen   error:   python   dataframe   sdn   解析   

原文地址:https://www.cnblogs.com/ychdzx/p/13266098.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!