1

I'm working on a project where I need to take an existing .txt file containing student names and number grades, assign letter grades to each student, and output name, grade, letter grade separated by commas. Then send the new output to a new file.

Example of text:

name_one, 85
name_two, 76.5

Desired Output:

name_one, 85, B
name_two, 76.5, C

Here's the code I have so far:

import numbers
import string


gradesDict = {}

with open("C:\\Users\\awolf\\.vscode\\extensions\\StudentExamRecords.txt", "r") as f:
    for line in f:
        (key, value) = line.strip().split(",")
        gradesDict[float(value)] = value
        
        def letter_grade(value):
            if value > 95:
                return "A"
            elif value > 91:
                return "A-"
            elif value > 87:
                return "B+"
            elif value > 83:
                return "B"
            elif value > 80:
                return "B-"
            elif value > 78:
                return "C+"
            elif value > 75:
                return "C"
            elif value > 70:
                return "D"
            else:
                return "F"

        print(key + "," + value)

I've created a dictionary to contain the data, opened the file path, stripped line notations and split string values into key/value, converted values to float, and created conditions to assign letter grades. What I am getting hung up on is adding the letter grade to the end of each line. I feel like I need to create a new variable "letterGrade" within the "def letter_grade" function and append the information to each line, but nothing I have tried is working.

Michael Delgado
  • 13,789
  • 3
  • 29
  • 54
  • 2
    Maybe you could include some code rather than [images of code](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question/285557#285557). – theherk Oct 22 '22 at 17:51
  • You shouldn't use images for posting your code. [Minimal-reproducible-example](https://stackoverflow.com/help/minimal-reproducible-example) – Eypros Oct 22 '22 at 17:52
  • Sorry, my first day on the site. I will try adding some code. ***post edited*** – awolfgram93 Oct 22 '22 at 17:53
  • 1
    It seems you could just add the letter grade to each line with: line += ", " + letter_grade(value) – Swifty Oct 22 '22 at 18:02
  • Does this answer your question? [How to add a new column to a CSV file?](https://stackoverflow.com/questions/11070527/how-to-add-a-new-column-to-a-csv-file) – kylieCatt Oct 22 '22 at 18:20

3 Answers3

1

Try:

def letter_grade(value):
    if value > 95:
        return "A"
    elif value > 91:
        return "A-"
    elif value > 87:
        return "B+"
    elif value > 83:
        return "B"
    elif value > 80:
        return "B-"
    elif value > 78:
        return "C+"
    elif value > 75:
        return "C"
    elif value > 70:
        return "D"
    else:
        return "F"


with open("your_file.txt") as f_in:
    for line in map(str.strip, f_in):
        if line == "":
            continue
        key, value = map(str.strip, line.split(","))
        print(key, value, letter_grade(float(value)), sep=", ")

Prints:

name_one, 85, B
name_two, 76.5, C
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
0

You can use pandas for that, and save the dataframe to an new file without header and index:

import pandas as pd

def letter_grade(value):
    if value > 95: return "A"
    elif value > 91: return "A-"
    elif value > 87: return "B+"
    elif value > 83: return "B"
    elif value > 80: return "B-"
    elif value > 78: return "C+"
    elif value > 75: return "C"
    elif value > 70: return "D"
    else: return "F"

df = pd.read_csv('StudentExamRecords.txt', sep=',', header=None)
df.columns = ['name', 'grade']
df['letter_grade'] = df['grade'].apply(letter_grade)
df.to_csv('ouput.txt', index=False, header=False)
René
  • 4,594
  • 5
  • 23
  • 52
0

You can adjust you grading scale easily through the grades dict. All values not greater than a VALUE specified will default to 'F' - please adjust to 'E' if appropriate for your academic setting.


import csv

# grading scale
grades = {
    'A': 95,
    'A-': 91,
    'B+': 87,
    'B': 83,
    'B-': 80,
    'C+': 78,
    'C': 75,
    # no C-
    'D': 70,
}

grade_results = []

with open('input.csv') as input_file:
    # pass the file to reader() to get the reader object
    csv_reader = reader(input_file)
    # iterate over each row in the csv using reader object
    for row in csv_reader:
        # row variable is a list that represents a row in csv
        grade = row[1]
        # check if grade is in grades dictionary
        # if grade between 95 and 100
        for key, value in grades.items():
            if grade >= value:
                # grade_results.append(key)
                grade_results.append([row[0], grade, key])
            else:
                grade_results.append([row[0], grade, 'F'])

# list to csv
with open('output.csv', 'w') as output_file:
    # create the csv writer object
    writer = csv.writer(output_file)
    # write the header
    writer.writerow(['Name', 'Grade', 'Letter Grade'])
    # write multiple rows
    writer.writerows(grade_results)