Question

I can open the file in the program, but I cannot figure out how to properly...

I can open the file in the program, but I cannot figure out how to properly split the data and assign a grade to the number values in the text file. I keep getting :: ValueError: invalid literal for int() with base 10: 'Roger Jones 75\n'

Below are the assignment details:

This program processes grades for a small class. It reads an input file named grade_input.txt where each record contains a student’s first name, last name and numeric grade (a whole number). The fields are separated by a space.

It calculates the student’s letter grade as follows:

  • A – greater than or equal to 90
  • B – greater than or equal to 80 but less than 90
  • C – greater than or equal to 70 but less than 80
  • D – greater than or equal to 60 but less than 70
  • F – less 60

It writes to an output file named grade_output.txt. The output file is similar to the input file, but has the student’s letter grade at the end of each line.

The program also calculates and displays the number of file records and the class average grade, and then lists the entire contents of the output file.

Here is a pseudocode definition of the program requirements:

Determine the full file names (including the folder) for grade_input.txt and grade_output.txt

Open grade_input.txt for input

Open grade_ output.txt for output

Initialize variables for counting records and computing average grade

For each record in the input file

                Read a line of data for that student

                Split the line into its individual fields

Store the individual fields into variables (first name, last name and grade)

                Calculate the letter grade

                Write data for that student to the output file

Update variables used to count records and compute average grade

Close the input and output files

If the record count is 0

                Display “no records in input file”

Else

Display the record count

Calculate and display the average grade using 1 fractional digit

List the contents of the output file

Some of code is already written for you. Download the GradeCalculator.py script starting file. It includes comments where you have to add your code.

Download the input file grade_input.txt. Put it in the same folder as the GradeCalculator.py. You can view the file in a simple text editor like notepad.

Make the necessary changes to the GradeCalculator.py script.

Test your program to make sure that it runs and produces correct results. Look at the output file in a text editor to make sure that it is correct.

Here is a sample test run (your file folders will be different):

grade calculator

This script file path is C:\ch04\GradeCalculator.py

This input file path is C:\ch04\grade_input.txt

This output file path is C:\ch04\grade_output.txt

6 records in the input file

average class grade 87.0

grade file contents:

Roger Jones 75 C

Maria Torres 90 A

Tong Nquyen 92 A

Rick DiPersio 100 A

Sarah Stevens 80 B

Edith Hills 85 B

Homework Answers

Answer #1
  • Complete program is well commented for better understanding.
  • Code snippet is provided below the typed code.
  • Please refer to snippet of code to understand the indentation of code.
  • Output snippet is attached below the code snippet.
  • Snippets of input.txt and output.txt are also attached at the end.

Program:

# opening input.txt file for reading purpose
f1 = open('input.txt')
# opening output.txt file for writing purpose
f2 = open('output.txt', 'w')
# NOTE: Here all files are in same directory as of program file(GradeCalculator.py)

# initializing variables for record count and average grade
rec_count = 0
avg_grade = 0

# for each record in input file
for record in f1.readlines():
    # incrementing record count
    rec_count += 1
    # splitting values in 3 different variables
    first_name, last_name, grade = record.split()
    # converting str grade to int grade
    grade = int(grade)
    # adding grade to avg grade
    avg_grade += grade
    # calculating letter grade
    if grade >= 90:
        l_grade = 'A'
    elif 90 > grade >= 80:
        l_grade = 'B'
    elif 80 > grade >= 70:
        l_grade = 'C'
    elif 70 > grade >= 60:
        l_grade = 'D'
    else:
        l_grade = 'F'
    # writing data for student in output file
    f2.write(first_name+" "+last_name+" "+str(grade)+" "+l_grade+"\n")
# closing input and output files
f1.close()
f2.close()

# printing output
print("grade calculator")
# NOTE: Here file paths given in question are printed to match with output
# These paths should be replaced with your own ones
print("This script file path is C:\\ch04\\GradeCalculator.py")
print("This input file path is C:\\ch04\\grade_input.txt")
print("This output file path is C:\\ch04\\grade_output.txt")

# if record count is 0, print no records
if rec_count == 0:
    print("no records in input file")
# else print record count
else:
    print(rec_count, "records in the input file")

# calculating average count and printing with 1 fractional digit
avg_grade = avg_grade/rec_count
print("average class grade", round(avg_grade, 1))

# opening output.txt in reading mode to print records
f = open('output.txt')
print("grade file contents:")
# printing records, with stripping newlines
for record in f.readlines():
    print(record.strip())

# closing opened file
f.close()

Code Snippet:

Output Snippet:

input.txt:

output.txt:

I hope you got the provided solution.

Thank You.

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Write a program that reads a file named input.txt and writes a file that contains the...
Write a program that reads a file named input.txt and writes a file that contains the same contents, but is named output.txt. The input file will contain more than one line when I test this. Do not use a path name when opening these files. This means the files should be located in the top level folder of the project. Do not use a copy method that is supplied by Java. Your program must read the file line by line...
Write a complete and syntactically correct Python program to solve the following problem: Write a program...
Write a complete and syntactically correct Python program to solve the following problem: Write a program for your professor that allows him to keep a record of the students’ average grade in his class. The program must be written in accordance with the following specs: 1. The input must be interactive from the keyboard. You will take input for 12 students. 2. You will input the students’ name and an average grade. The student cannot enter an average below zero...
Lab 6    -   Program #2   -   Write one number to a text file. Use the write()...
Lab 6    -   Program #2   -   Write one number to a text file. Use the write() and read() functions with binary                                                        data, where the data is not char type.              (Typecasting is required) Fill in the blanks, then enter the code and run the program. Note:   The data is int type, so typecasting is            required in the write() and read() functions. #include <iostream> #include <fstream> using namespace std; int main() {    const int SIZE = 10;   ...
PART B- Javascript Using a text editor (VS Code or Notepad) and a web browser, you...
PART B- Javascript Using a text editor (VS Code or Notepad) and a web browser, you will demonstrate how to create an HTML file, externally link a JavaScript file, and write some source code in the JavaScript file. a..Create two blank files to be an HTML file and a JavaScript file. The file names should be partA.html and partA.js. b.. Create a basic HTML webpage structure. c..Link the JavaScript file to the HTML file using the <script> tag. d.. Prompt...
AWK utility Consider the following awk program: { $1="A" ; print $0 } What is the...
AWK utility Consider the following awk program: { $1="A" ; print $0 } What is the output if the input consists of the following line: program program Question 1 options: program program program A program The awk program fails None of the above Question 2 The awk command can use an inline script specified on the command line or a file based script specified by the -f option Question 2 options:    True    False Question 3 Match each awk...
Java: A teacher has five students who have taken four tests. The teacher uses the following...
Java: A teacher has five students who have taken four tests. The teacher uses the following grading scale to assign a letter grade to a student, based on the average of his or her four test scores: Test Score Letter Grade 90–100 A 80–89 B 70–79 C 60–69 D 0–59 F Write a class that uses a String array (or an ArrayList object) to hold the five students’ names, an array of five characters to hold the five students’ letter...
Program Behavior Each time your program is run, it will prompt the user to enter the...
Program Behavior Each time your program is run, it will prompt the user to enter the name of an input file to analyze. It will then read and analyze the contents of the input file, then print the results. Here is a sample run of the program. User input is shown in red. Let's analyze some text! Enter file name: sample.txt Number of lines: 21 Number of words: 184 Number of long words: 49 Number of sentences: 14 Number of...
Each part of this lab will use the same input file, named “lab3-in.dat.” This file will...
Each part of this lab will use the same input file, named “lab3-in.dat.” This file will be located in the same directory as the executables (do not specify a path for the file in the Select statements). This file is a roster of animals in a travelling carnival. The record format for the file is as follows: Field Description Length Data Type Name 12 String Gender 1 String Species 15 String The end result of each part of this assignment...
This is C++ Note, for part 2 of this assignment, you DO NOT NEED to use...
This is C++ Note, for part 2 of this assignment, you DO NOT NEED to use arrays or vectors. All changes, calculations, etc should be performed in place ( in the file). You may need one or two structures that temporary hold data needed to be displayed, changed, etc. Part 2: Binary Files Write a program that uses a structure to store the following inventory data in a file: The data can be either read from a text file or...
we will be taking data in as a file. you cannot use the data values in...
we will be taking data in as a file. you cannot use the data values in your source file but you must read in everything into variables and use it from there. First we need to include <fstream> at the top of our file. We will need to create an input file stream to work and ifstream. ifstream is a datatype. Create a variable with the datatype being ifstream. Variable is drfine by using the member accessor operator to call...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT