如何使用Python csv.DictReader处理多分隔符CSV文件?
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

