withopen(csv_file,'r',encoding='utf-8') as csv_f: withopen(json_file,'w',encoding='utf-8') as json_f: # 设定键名 filednames=('index','city','education','industry','job_keyword','publish_time','salary','scale','technology_keyword','treatment') # 以字典形式读取csv文件内容,每一个字典中的键名对应filednames # 有两个参数,第一个为文件描述符,第二个为字典对应的键名 reader = csv.DictReader(csv_f,filednames) # 将字典序列化为json字符串,DictReader返回的可迭代的对象 out = json.dumps([i for i in reader],ensure_ascii=False) # 不让中文显示成ascii # 将序列化后的文件写入文件中 json_f.write(out)
说明:最后两句也可以写成json.dump([i for i in reader],json_f,ensure_ascii=False)