CSV文件处理问题:读取文件、计算行内整数总和及等级评定
Solution for Processing Your CSV File
Hey there! Let's work through this CSV processing task together. I'll use Python since it's straightforward for handling CSV data and calculations—no fancy tools required.
Step 1: Define the Letter Grade Rule
First, we need a clear rule to map average scores to final letter grades. I'll use a common grading scale, but feel free to adjust this to match your needs:
- 90+ → A
- 80-89 → B
- 70-79 → C
- 60-69 → D
- Below 60 → F
Step 2: Full Python Code
Here's a complete script that reads your existing CSV, computes the required values, and writes the updated data to a new CSV file (so we don't overwrite your original data by accident):
import csv def calculate_final_grade(average): """Map average score to a letter grade""" if average >= 90: return 'A' elif average >= 80: return 'B' elif average >= 70: return 'C' elif average >= 60: return 'D' else: return 'F' # Replace 'input.csv' with your actual CSV file path input_file = 'input.csv' # Output file will have the original data plus sum, average, final grade output_file = 'updated_scores.csv' with open(input_file, mode='r', newline='') as infile, \ open(output_file, mode='w', newline='') as outfile: reader = csv.reader(infile) writer = csv.writer(outfile) # Write the updated header first header = next(reader) header.extend(['Total Sum', 'Average Score', 'Final Grade']) writer.writerow(header) # Process each row for row in reader: # Extract data from the row name = row[0] # Get the 8 integer columns (indices 1 to 8) and convert to integers scores = list(map(int, row[1:9])) original_grade = row[9] # Calculate sum and average total_sum = sum(scores) average_score = total_sum / 8 # Get final letter grade final_grade = calculate_final_grade(average_score) # Create the updated row updated_row = row + [total_sum, round(average_score, 2), final_grade] writer.writerow(updated_row) print(f"Processing complete! Updated data saved to {output_file}")
Key Notes to Adjust for Your Use Case
- File Paths: Make sure
input.csvpoints to your actual CSV file. If it's in a different folder, use the full path (e.g.,'C:/Documents/your_file.csv'on Windows or'/home/user/your_file.csv'on macOS/Linux). - Grading Scale: Modify the
calculate_final_gradefunction if you need different thresholds for letter grades. - Decimal Precision: The code rounds the average to 2 decimal places—change
round(average_score, 2)to adjust this (or remove theround()function if you want full precision). - CSV Delimiter: If your CSV uses a delimiter other than commas (like tabs), add
delimiter='\t'to bothcsv.reader()andcsv.writer().
How It Works
- We open both the input and output CSV files safely using
withstatements (this ensures files are closed automatically). - We read the header row first, then add the new column names for sum, average, and final grade.
- For each data row:
- We pull out the name, the 8 integer scores, and the original grade.
- Compute the total sum of the scores and their average.
- Use our grading function to get the final letter grade.
- Append the new values to the original row and write it to the output file.
This should handle your 20-row CSV perfectly—let me know if you run into any snags with file paths or grading rules!
内容的提问来源于stack exchange,提问作者Angel Torres
相关产品推荐
相关产品推荐

