You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python csv.DictReader处理多分隔符CSV文件?

Can csv.DictReader handle this mixed-delimiter CSV?

Short answer: No, that won’t work correctly. Here’s why and how to fix it.

Why your current approach fails

When you initialize csv.DictReader(data, delimiter=','), it uses commas as the separator for every line in the file. While this correctly parses the comma-separated header row to get field names, it will treat each subsequent pipe-separated line as a single string value. This means each dictionary in your reader will only have a value for the first field (slNo), and all other fields (quatinty, data1, etc.) will be None—definitely not what you want.

The fix: Split header and data rows separately

Since your header uses a different delimiter than your data, you need to handle them explicitly. Here’s a straightforward implementation:

import csv

with open("your_file.csv", "r") as file:
    # Read and parse the comma-separated header to get field names
    field_names = file.readline().strip().split(",")
    
    # Initialize DictReader with pipe delimiter and our pre-defined field names
    reader = csv.DictReader(file, fieldnames=field_names, delimiter="|")
    
    # Process each row as normal
    for row in reader:
        print(row)

How this works:

  • First, we read the header line manually and split it with commas to get the correct field names.
  • Then, we pass the remaining file content to csv.DictReader, telling it to use pipes as the delimiter for data rows, and to use our pre-parsed field names for the dictionary keys.
  • This ensures both the header and data rows are parsed correctly, giving you valid dictionaries for each entry.

内容的提问来源于stack exchange,提问作者Nithish Albin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 20:52:41