Question

Hint: Skip the first line of the file as it is a header line Hint: All values come in as strings, so convert to floats before mathematical comparisons and calculations. File Format Name,Test1,Test2,Test3 lla,1,67,64 Xavier,83,11,54 Phillip,39,95,16

Python function:

This is my code and I don't know how to add the column to the csv file:

def write_with_averages(read,write):
with open (read,'r') as f_in:
header = f_in.readline()
reader=csv.reader(f_in)
with open (write,'w') as f_out:
writer=csv.writer(f_out)
New_data=[]
for Name, Test1, Test2, Test3 in reader:
Total=(float(Test1)+float(Test2)+float(Test3))
average=Total/3
New_data.append(average)

0 0
Add a comment Improve this question Transcribed image text
Answer #1

PYTHON CODE:

def write_with_average(read,write):

    # opening the file for reading
    file1=open(read)

    # opening the file for writing the output
    output=open(write,'w')

    # writing the headers to the output file
    output.write('Name,Test1,Test2,Test3,Average\n')

    # for every line in the file1
    for number,line in enumerate(file1):

        # skipping the header
        if number == 0:
            continue

        # removing the spaces at the end and beginnging of the line
        line=line.strip()

        # splitting the line by comma
        data=line.split(',')

        # variable to store the total marks
        total=0

        # writing the Name to the output file
        output.write(data[0]+',')

        # calculating total
        for mark in data[1:]:
            total+=float(mark)

            # writing the mark to the output file
            output.write(mark+',')

        # calculating the average
        average=total/(len(data)-1)

        # writing average to the output file
        output.write(str(average)+'\n')

    # closing the files
    output.close()
    file1.close()
      
#testing
if __name__=='__main__':

    # calling the function
    write_with_average('random_grades.csv','grades_and_averages.csv')


  
  


CONTENTS OF random_grades.csv:

Name,Test1,Test2,Test3
Ila,1,67,64
Xavier,83,11,54
Phillip,39,95,16

CONTENTS OF grades_and_average.csv:

Name,Test1,Test2,Test3,Average
Ila,1,67,64,44.0
Xavier,83,11,54,49.333333333333336
Phillip,39,95,16,50.0

Add a comment
Know the answer?
Add Answer to:
Python function: This is my code and I don't know how to add the column to...
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. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • *PYTHON* For this assignment, you will need to take the 4th assignment (code at bottom) and exp...

    *PYTHON* For this assignment, you will need to take the 4th assignment (code at bottom) and expand on your code. You will need to compile the highs and lows for 2017, showing the average for each month and the average high and low for the entire year. Output will be like this: Average Low for month 1: 27 Average High for month 1: 49 Average Low for month 2: 28 Average High for month 2: 54 Average Low for month...

  • Please help me fix my errors. I would like to read and write the text file...

    Please help me fix my errors. I would like to read and write the text file in java. my function part do not have errors. below is my code import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.FileWriter; import java.io.IOException; public class LinkedList {    Node head;    class Node    {        int data;        Node next;       Node(int d)        {            data = d;            next = null;        }    }    void printMiddle()    {        Node slow_ptr...

  • Write a function named "loadStateDict(filename) that takes a filename and returns a dictionary of 2-character state...

    Write a function named "loadStateDict(filename) that takes a filename and returns a dictionary of 2-character state codes and state names. The file has four columns and they are separated by commas. The first column is the state full name and the second column is the state code. You don't have to worry about column 3 & 4. You should eliminate any row that is without a state code. Save the two columns into a dictionary with key = state code...

  • For the following task, I have written code in C and need help in determining the...

    For the following task, I have written code in C and need help in determining the cause(s) of a segmentation fault which occurs when run. **It prints the message on line 47 "printf("Reading the input file and writing data to output file simultaneously..."); then results in a segmentation fault (core dumped) I am using mobaXterm v11.0 (GNU nano 2.0.9) CSV (comma-separated values) is a popular file format to store tabular kind of data. Each record is in a separate line...

  • I need help in Python. This is a two step problem So I have the code...

    I need help in Python. This is a two step problem So I have the code down, but I am missing some requirements that I am stuck on. Also, I need help verifying the problem is correct.:) 7. Random Number File Writer Write a program that writes a series of random numbers to a file. Each random number should be in the range of 1 through 500. The application should let the user specify how many random numbers the file...

  • Hello! I have this python Homework due tonight that I don't know how to do. Here...

    Hello! I have this python Homework due tonight that I don't know how to do. Here is a document with the data in the csv file, as I didn't know how to share it https://docs.google.com/document/d/1bDJVR2MqWKInvw5u0r3fOG3-CBmu3BEiPZwlaq_CShQ/edit?usp=sharing Activity #3: On the class website is a CSV file containing weather data from Coulter Field (in Bryan) for 3 years (1 day is missing for some reason!); the data was taken from Weather Underground (wunderground.com). There are different versions of the file for Windows...

  • I am having a little trouble with my Python3 code today, I am not sure what...

    I am having a little trouble with my Python3 code today, I am not sure what I am doing wrong. Here are the instructions: and here is my code: update: I have seen I did not close x in sumFile and I am still only getting a 2/10 on the grader. any help appreciated. Lab-8 For today's lab you going to write six functions. Each function will perform reading and/or write to a file Note: In zybooks much like on...

  • the following python code edits BMP image file to negative but I need help with modifying...

    the following python code edits BMP image file to negative but I need help with modifying this code so it turns it the same BMP image file into a black and white instead of a negative. heres python code I have so far [pasted below] ## # This program processes a digital image by creating a negative of a BMP image. # from io import SEEK_CUR from sys import exit def main() : filename = input("Please enter the file name:...

  • Using python 3.6 How do I incorporate 0 or negative input to raise an error and...

    Using python 3.6 How do I incorporate 0 or negative input to raise an error and let the user try again? like <=0 #loop to check valid input option. while True: try: choice = int(input('Enter choice: ')) if choice>len(header): print("Invalid choice!! Please try again and select value either:",end=" ") for i in range(1,len(header)+1): print(i,end=",") else: break choice = int(input('\nEnter choice: ')) except ValueError as ve:print('Invalid response, You need to select the number choice from the option menu') # Catch your...

  • Use python programing. We will look at the idea of how many olympic medals were won...

    Use python programing. We will look at the idea of how many olympic medals were won by a country compared to it's population. The 2014 population of the medal-earning countries that participated in the Sochi winter olymipics was 2,516,757,975 people. Further, 295 medals were won in the winter olympics in Sochi. This means that there were: 295 / 2,516,757,975 * 10,000,000 =1.172 medals awarded for every 10,000,000 people For each country, we can use it's population and it's medal count...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT