目录
- 专栏导读
- 1、背景
- 2、库的安装
- 3、代码1—自定义表头
- 4、代码2—全字段
- 5、代码3—全字段
- 总结
专栏导读
-
🌸 欢迎来到Python办公自动化专栏—Python处理办公问题,解放您的双手
-
🏳️🌈 博客主页:请点击——> 一晌小贪欢的博客主页求关注
-
👍 该系列文章专栏:请点击——>Python办公自动化专栏求订阅
-
🕷 此外还有爬虫专栏:请点击——>Python爬虫基础专栏求订阅
-
📕 此外还有python基础专栏:请点击——>Python基础学习专栏求订阅
-
文章作者技术和水平有限,如果文中出现错误,希望大家能指正🙏
-
❤️ 欢迎各位佬关注! ❤️
1、背景
-
我们有时候经常会将csv文件转为json数据(本地),然后加载json数据作为匹配项,可以将里面的数据匹配给其他的表格中
2、库的安装
3、代码1—自定义表头
def write_json_cjb_last_month(csv_file_path):
last_cjb = {}
with open(csv_file_path, 'r') as f:
rows = csv.reader(f)
header = next(rows)
结算账号_index = header.index('结算账号-CMDM')
地区_index = header.index('结算归属地区.1')
小组_index = header.index('小组')
应收金额_index = header.index('应收金额')
for row in rows:
结算账号 = row[结算账号_index]
应收金额 = float(row[应收金额_index]) if row[应收金额_index].strip() else 0
if 结算账号 in last_cjb:
last_cjb[结算账号]["应收金额"] = str(float(last_cjb[结算账号]["应收金额"]) + 应收金额)
else:
last_cjb[结算账号] = {
"地区": row[地区_index],
"小组": row[小组_index],
"应收金额": str(应收金额)
}
with open('json数据/data.json', 'w', encoding='utf-8') as f:
json.dump(last_cjb, f, ensure_ascii=False, indent=4)
write_json_cjb_last_month(csv_file_path)
4、代码2—全字段
def csv_to_json(csv_file_path):
with open(csv_file_path, 'r',encoding='utf-8') as f:
reader = csv.reader(f)
header = next(reader)
data = [dict(zip(header, row)) for row in reader]
with open('data.json', 'w',encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False)
csv_to_json(file_name)
5、代码3—全字段
def csv_to_json(csv_file_path, json_file_path):
with open(csv_file_path, mode='r', encoding='utf-8', newline='') as csvfile:
reader = csv.DictReader(csvfile)
with open(json_file_path, mode='w', encoding='utf-8') as jsonfile:
jsonfile.write('[')
first_line = True
for row in reader:
if not first_line:
jsonfile.write(',\n')
json.dump(row, jsonfile, ensure_ascii=False)
first_line = False
jsonfile.write('\n]')
csv_to_json(file_name, json_file)
with open(json_file, mode='r', encoding='utf-8') as f:
data = json.load(f)
for i in data:
print(i)
总结
-
希望对初学者有帮助
-
致力于办公自动化的小小程序员一枚
-
希望能得到大家的【一个免费关注】!感谢
-
求个 🤞 关注 🤞
-
此外还有办公自动化专栏,欢迎大家订阅:Python办公自动化专栏
-
求个 ❤️ 喜欢 ❤️
-
此外还有爬虫专栏,欢迎大家订阅:Python爬虫基础专栏
-
求个 👍 收藏 👍
-
此外还有Python基础专栏,欢迎大家订阅:Python基础学习专栏