标签:imp err load() pen error: python dataframe sdn 解析
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 的读写吧
# 读
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=‘ ‘)
# 读
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)
dumps() 将一个python对象编码为json对象
loads() 讲一个json对象解析为python对象
dump() 将python对象写入文件
load()从文件中读取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}
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}
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
标签:imp err load() pen error: python dataframe sdn 解析
原文地址:https://www.cnblogs.com/ychdzx/p/13266098.html