导入CSV并求和Revenue字段:代码报错及结果异常求助
Hey there! Let's work through fixing your CSV Revenue sum issues together—those two problems you're hitting are super common, so we'll get them sorted in no time.
1. Fixing the ValueError: invalid literal for int() with base 10: ''
This error pops up because there are empty cells (blank strings) in your "Revenue" column. When you try to convert an empty string to an integer with int(), Python doesn't know what to do with it—hence the crash. We just need to add a check to skip or handle those empty values.
2. Fixing the Incorrect Sum Result
That issue where you only get 10 instead of 100? Chances are your original code wasn't looping through all rows properly—maybe it only processed the first row and stopped, or your accumulation logic was off.
Working Code Example
Let's assume your CSV looks something like this (with or without a header row):
ID,Revenue 1,10 2,20 3,30 4,40 5, 6,50
Here's the fixed code that handles both problems:
import csv total_revenue = 0 # Replace 'your_file.csv' with the actual path to your CSV with open('your_file.csv', 'r') as csv_file: csv_reader = csv.reader(csv_file) # Uncomment this line if your CSV has a header row (like "ID,Revenue") next(csv_reader) for row in csv_reader: # Grab the second column (index 1, since Python counts from 0) revenue_entry = row[1].strip() # Remove extra spaces just in case # Only process non-empty entries to avoid the ValueError if revenue_entry: total_revenue += int(revenue_entry) print(f"Total Revenue: {total_revenue}")
Key Explanations
next(csv_reader): Skips the header row if your CSV has one—prevents trying to convert text like "Revenue" into a number.row[1].strip(): Cleans up any extra spaces around the revenue value (sometimes CSVs have accidental spaces that look like empty cells).if revenue_entry:: Checks if the cell isn't empty before converting it to an integer—this eliminates the ValueError entirely.- Full loop through rows: Ensures every row's Revenue value gets added to the total, so you won't just get the first value anymore.
Testing Your Simplified Data
If your test data is just rows with Revenue values 10,20,30,40 (with or without a header), run this code (remove next(csv_reader) if there's no header) and you'll get the correct total of 100.
Bonus: Handle Decimal Values
If your Revenue has decimals (e.g., 15.50), just swap int() with float():
total_revenue += float(revenue_entry)
内容的提问来源于stack exchange,提问作者CJC2104

