Python怎么将csv格式转换成JSON格式文件
这篇文章主要介绍“Python怎么将csv格式转换成JSON格式文件”,在日常操作中,相信很多人在Python怎么将csv格式转换成JSON格式文件问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Python怎么将csv格式转换成JSON格式文件”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
这篇文章主要介绍“Python怎么将csv格式转换成JSON格式文件”,在日常操作中,相信很多人在Python怎么将csv格式转换成JSON格式文件问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Python怎么将csv格式转换成JSON格式文件”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
创新互联公司专业为企业提供河北网站建设、河北做网站、河北网站设计、河北网站制作等企业网站建设、网页设计与制作、河北企业网站模板建站服务,十多年河北做网站经验,不只是建网站,更提供有价值的思路和整体网络服务。
csv文件内容如下:1 Twin Oaks Place 10 Marquette Rd. 12 Craven Way 12 Fort Sheriden Ave. 12 Skokie Valley Rd. 12 Walker Ave. 120 high St.
一、使用内置函数处理# /usr/bin/env python# -*- coding:utf-8 -*-import sysimport jsonreload(sys)sys.setdefaultencoding('utf-8')#根据列表中是否为空,将不为空的配成键值对更新到字典中def list_name(keyname, value1, dict1=None): dict1 = dict(zip(keyname, value1)) return dict1with open(r'D:\address.csv', 'rb') as f: for line in f: if line == []: line ="" else: if line[-1] == "\n": line = line[:-1] if line[-1] == "\r": line = line[:-1] akk = [y for y in line.split(" ")] key1 = ['street','namefirst','namelast','address'] a1 = {} arr = list_name(key1,akk,a1) arr = json.dumps(arr) print arr
输出如下:{"namelast": "Oaks", "street": "1", "namefirst": "Twin", "address": "Place"}{"namelast": "Rd.", "street": "10", "namefirst": "Marquette"}{"namelast": "Way", "street": "12", "namefirst": "Craven"}{"namelast": "Sheriden", "street": "12", "namefirst": "Fort", "address": "Ave."}{"namelast": "Valley", "street": "12", "namefirst": "Skokie", "address": "Rd."}{"namelast": "Ave.", "street": "12", "namefirst": "Walker"}{"namelast": "St.", "street": "120", "namefirst": "high"}
# /usr/bin/env python# -*- coding:utf-8 -*-import sysimport jsonreload(sys)sys.setdefaultencoding('utf-8')#根据列表中是否为空,将不为空的配成键值对更新到字典中def list_name(keyname, value1, dict1=None): for i in range(0, len(value1)): if value1[i] == "": break else: dit = {keyname[i]: value1[i]} dict1.update(dit) i += 1; return dict1with open(r'D:\address.csv', 'rb') as f: for line in f: if line == []: line ="" else: if line[-1] == "\n": line = line[:-1] if line[-1] == "\r": line = line[:-1] akk = [y for y in line.split(" ")] key1 = ['street','namefirst','namelast','address'] a1 = {} arr = list_name(key1,akk,a1) arr = json.dumps(arr) print arr
输出如下:
{"namelast": "Oaks", "street": "1", "namefirst": "Twin", "address": "Place"}{"namelast": "Rd.", "street": "10", "namefirst": "Marquette"}{"namelast": "Way", "street": "12", "namefirst": "Craven"}{"namelast": "Sheriden", "street": "12", "namefirst": "Fort", "address": "Ave."}{"namelast": "Valley", "street": "12", "namefirst": "Skokie", "address": "Rd."}{"namelast": "Ave.", "street": "12", "namefirst": "Walker"}{"namelast": "St.", "street": "120", "namefirst": "high"}
当前标题:Python怎么将csv格式转换成JSON格式文件
文章链接:http://azwzsj.com/article/cgpi.html