excel文件有两列,循环读取文件两列赋值到字典列表。字典的有两个key,分别为question和answer。将最终结果输出到json文件

import pandas as pd
import json

# 1. 读取 Excel 文件(假设列名为 question 和 answer)
try:
    df = pd.read_excel("input.xlsx", usecols=["question", "answer"])  # 明确指定列
except Exception as e:
    print(f"读取文件失败: {str(e)}")
    exit()

# 2. 转换为字典列表
result = [
    {"question": str(row["question"]), "answer": str(row["answer"])}
    for _, row in df.iterrows()
]

# 3. 写入 JSON 文件
with open("train_qa.json", "w", encoding="utf-8") as f:
    json.dump(result, f, ensure_ascii=False, indent=2)

print("转换成功!")

你可能感兴趣的:(python,excel,json,python)