AWS Lambda中Python循环跳过首个索引及列表索引越界问题解决求助
Hey there! I’ve gone through your code and I can see exactly what’s causing those issues. Let’s fix them both with some straightforward adjustments, plus a more robust way to handle CSV parsing.
1. Skipping the CSV Header Row
Right now, your loop runs through every line in the CSV, including the first header row. To skip it cleanly, the best approach is to use Python’s built-in csv module (we’ll use this in the revised code) — it lets you call next(reader) to jump past the header line instantly. If you wanted to stick with your original split method, you could also loop over students[1:] instead of students to start from the second element (index 1), but the csv module is far more reliable.
2. Fixing the "List Index Out of Range" Error
This error pops up for a few common reasons:
- Your CSV might have an empty final line (when splitting by
\n, you get an empty string that splits into a tiny, incomplete list). - Some rows might have fewer columns than expected (typos, missing data, or formatting quirks in the CSV).
- Manual splitting with
split(",")doesn’t handle cases where commas are inside quoted values (like"Doe, John"), which breaks your column count entirely.
The csv module solves all these edge cases automatically, so we’ll use that to make your script resilient.
Revised Code
Here’s your updated script that addresses both problems:
import json import boto3 import csv from io import StringIO s3_client = boto3.client("s3") dynamodb = boto3.resource("dynamodb") student_table = dynamodb.Table('s3todynamodb') def lambda_handler(event, context): source_bucket_name = event['Records'][0]['s3']['bucket']['name'] file_name = event['Records'][0]['s3']['object']['key'] # Get file content and wrap it in a StringIO for csv reader compatibility file_object = s3_client.get_object(Bucket=source_bucket_name, Key=file_name) file_content = file_object['Body'].read().decode("utf-8") csv_reader = csv.reader(StringIO(file_content)) # Skip the header row next(csv_reader) for row in csv_reader: # Skip empty rows to avoid index errors if not row: continue # Validate row has enough columns before accessing indexes if len(row) < 19: print(f"Skipping invalid row: {row} (insufficient columns)") continue # Insert valid row into DynamoDB student_table.put_item( Item = { "Agent" : row[0], "Agent answer rate" : row[1], "Agent idle time" : row[2], "Contacts missed" : row[3], "Agent on contact time" : row[4], "Nonproductive time" : row[5], "Occupancy" : row[6], "Online time" : row[7], "Average after contact work time" : row[8], "Average agent interaction time" : row[9], "Average customer hold time" : row[10], "Average handle time" : row[11], "Contacts handled" : row[12], "Contacts handled incoming" : row[13], "Contacts handled outbound" : row[14], "Contacts put on hold" : row[15], "Contacts transferred out" : row[16], "Contacts transferred out external" : row[17], "Contacts transferred out internal" : row[18] } ) return { 'statusCode': 200, 'body': json.dumps('Data imported successfully!') }
Key Improvements Explained:
csvModule: Properly parses CSV content, handling quoted commas, line breaks, and inconsistent formatting that manual splitting misses.- Header Skip:
next(csv_reader)moves past the first header line without extra loop logic. - Empty Row Check: Skips blank lines that would otherwise cause index errors.
- Column Validation: Checks if the row has at least 19 columns before trying to access indexes, preventing out-of-range crashes.
- StringIO: Converts the decoded file content into a file-like object that
csv.readercan process seamlessly.
This should resolve both your issues and make your script far more robust to messy CSV data!
内容的提问来源于stack exchange,提问作者Rehan CH

