将csv导出json格式
将csv导出json格式
import os,csv,json cf = open('D:\OneDrive\\Tech\\Script\\Powershell_Script\\Uxin_work\\VM-Export2012\\VMs.csv','r') for x in csv.DictReader(cf): d = json.dumps(x,indent=6,separators=(',',':'), ensure_ascii=False) #,sort_keys=True print d cf.close()
将csv导出json格式(适用于python manage.py loaddata导入的json格式化文件)
import os,csv,json #cf = open('vms.csv','r') cf = open('D:\OneDrive\\Tech\\Script\\Powershell_Script\\Uxin_work\\VM-Export2012\\VMs.csv','r') cf_count = len(cf.readlines()) cf.seek(0) if(os.path.exists('vms22.json')): os.remove('vms22.json') c2 = open('vms22.json','a') cf.read(3) #去掉文本开头几个文件编码显示字符 c2.write('[' + '\n' + '{' + '\n') n=1 for x in csv.DictReader(cf): d = json.dumps(x,indent=6,separators=(',',':'), ensure_ascii=False) #indent=6缩进6个字符 separators=(',',':')去除,和:后面的空字符串等 sort_keys=True按key排序 ensure_ascii=False解决中文乱码问题 d2 = ' "fields": ' + d.replace('PSComputerName\\','PSComputerName') + ',' + '\n' + ' "model": "sinfors.hvvms",' + '\n' + ' "pk": ' + str(n) + '\n' #d2 = ' "fields": ' + d + ',' + '\n' + ' "model": "sinfors.hvvms",' + '\n' + ' "pk": ' + str(n) + '\n' c2.write(d2) if n < cf_count-1: c2.write('},' + '\n' + '{' + '\n') else: c2.write('}' + '\n' + ']' + '\n') n=n+1 cf.close() c2.close()