如何将两个带共同Key列的CSV文件合并为一个CSV文件
分号分隔多语言CSV合并实现方案
你需要实现的是两个以分号为分隔符的CSV文件,基于公共Key字段进行关联,拼接不同语言的翻译列,以下是两种可直接使用的实现方案:
方案1:Python标准库实现(无需额外安装依赖)
适合不想引入第三方库的轻量场景:
# 存储荷兰语翻译键值对 dutch_map = {} with open("CSV_FileOne.csv", "r", encoding="utf-8") as f: # 读取表头后逐行解析内容 f.readline() for line in f: line = line.strip() if not line: continue key, value = line.split(";", 1) dutch_map[key] = value # 存储德语翻译键值对 deutsch_map = {} with open("CSV_FileTwo.csv", "r", encoding="utf-8") as f: f.readline() for line in f: line = line.strip() if not line: continue key, value = line.split(";", 1) deutsch_map[key] = value # 输出合并后的文件 with open("merged_result.csv", "w", encoding="utf-8") as f: # 写入表头 f.write("Key;Dutch;Deutsch\n") # 遍历所有共有Key输出内容 for common_key in dutch_map.keys() & deutsch_map.keys(): f.write(f"{common_key};{dutch_map[common_key]};{deutsch_map[common_key]}\n")
方案2:pandas实现(代码更简洁,适合数据量较大的场景)
需要提前安装pandas库:pip install pandas
import pandas as pd # 读取两个CSV文件,指定分隔符为分号 df_dutch = pd.read_csv("CSV_FileOne.csv", sep=";", encoding="utf-8") df_deutsch = pd.read_csv("CSV_FileTwo.csv", sep=";", encoding="utf-8") # 按Key字段关联合并,outer模式保留所有Key,inner模式仅保留共有Key merged_df = pd.merge(df_dutch, df_deutsch, on="Key", how="inner") # 导出合并结果 merged_df.to_csv("merged_result.csv", sep=";", index=False, encoding="utf-8")
内容的提问来源于stack exchange,提问作者xsold
相关产品推荐
相关产品推荐

