CSV文件读写异常:KeyError与AttributeError问题求助
Let's break down your two errors one by one and work through fixes for each:
Since most fields work fine, the issue is likely specific to how these two field names are defined or read. Here are the most common culprits:
Case mismatch or hidden whitespace
CSV field names are case-sensitive, and invisible characters (like leading/trailing spaces, tabs, or newlines) can sneak in easily. For example, if your CSV hasmonth(lowercase) orMonth(with spaces) but yourfieldnamevariable uses'Month', the keys won't match.
Fix:- Open your CSV file in a text editor (not Excel, which might hide whitespace) to check the exact spelling/casing of the Month/Year columns.
- Normalize field names when reading: strip whitespace and standardize case, like this:
import csv with open('your_file.csv', 'r') as f: reader = csv.DictReader(f) # Normalize field names for each row for row in reader: normalized_row = {k.strip().title(): v for k, v in row.items()} # Now access normalized_row['Month'] or normalized_row['Year'] - If you're using a custom
fieldnamelist, make sure it exactly matches the CSV's column headers (including case and no extra spaces).
Incorrectly specifying fieldnames in DictReader
If you're initializingcsv.DictReaderwithout passing yourfieldnamevariable, it will use the first row of the CSV as field names. If those don't match yourfieldnamelist, accessing keys from your list will throw errors.
Fix:
Explicitly pass your field names when creating the reader:with open('your_file.csv', 'r') as f: reader = csv.DictReader(f, fieldnames=self.fieldnames) # Skip the header row if your CSV already has one (since you're using custom fieldnames) next(reader)
The error wrong_fields = rowdict.keys() - self.fieldnames tells us that rowdict is a string, not a dictionary. Here's why that might happen:
You're using a regular CSV reader instead of DictReader
If you usedcsv.reader()instead ofcsv.DictReader(), each row is returned as a list of strings—not a dictionary. If you accidentally assigned that list (or a string from it) torowdict, calling.keys()will fail.
Fix:
Switch tocsv.DictReaderto get dictionary rows:# Wrong: returns lists, not dicts # reader = csv.reader(f) # Correct: returns dictionaries with field names as keys reader = csv.DictReader(f, fieldnames=self.fieldnames)Accidental type conversion to string
Maybe somewhere in your code, you converted the row dictionary to a string (e.g., for debugging withprint(str(rowdict))) and then stored that string instead of the original dict.
Fix:
Check your code for places where you might be reassigningrowdictto a string. For example, remove any lines like:rowdict = str(rowdict) # This turns the dict into a string—don't do this!Error handling returning a string instead of a dict
If you have try/except blocks around row processing, you might be catching an error and assigning an error message (a string) torowdictinstead of skipping the bad row.
Fix:
Adjust your error handling to skip invalid rows or log the error without overwritingrowdict:for row in reader: try: rowdict = row # Keep as dict # Process rowdict here except Exception as e: print(f"Error processing row: {e}") continue # Skip the bad row instead of assigning a string to rowdict
Once you fix these issues, your code should be able to access all fields and write to the new file without errors.
内容的提问来源于stack exchange,提问作者Bbrown

