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

CSV文件读写异常:KeyError与AttributeError问题求助

Let's break down your two errors one by one and work through fixes for each:

1. KeyError: 'Month' / 'Year'

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 has month (lowercase) or Month (with spaces) but your fieldname variable 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 fieldname list, make sure it exactly matches the CSV's column headers (including case and no extra spaces).
  • Incorrectly specifying fieldnames in DictReader
    If you're initializing csv.DictReader without passing your fieldname variable, it will use the first row of the CSV as field names. If those don't match your fieldname list, 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)
    
2. AttributeError: 'str' object has no attribute 'keys()'

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 used csv.reader() instead of csv.DictReader(), each row is returned as a list of strings—not a dictionary. If you accidentally assigned that list (or a string from it) to rowdict, calling .keys() will fail.
    Fix:
    Switch to csv.DictReader to 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 with print(str(rowdict))) and then stored that string instead of the original dict.
    Fix:
    Check your code for places where you might be reassigning rowdict to 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) to rowdict instead of skipping the bad row.
    Fix:
    Adjust your error handling to skip invalid rows or log the error without overwriting rowdict:

    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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:34:04