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
  • Functionality to build (4 functions) read_csv_header Define a function named read_csv_header with one parameter. This parameter...

    Functionality to build (4 functions) read_csv_header Define a function named read_csv_header with one parameter. This parameter will be a csv reader object (e.g., the value returned when calling the function csv.reader). The first row read using the parameter is the file's header row. The header row contains the keys for the data stored in the CSV file. This function must return a list containing the strings from that header row. The function parameter will be a csv reader object and...

  • *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...

  • 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...

  • 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 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...

  • 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...

  • Could anyone help add to my python code? I now need to calculate the mean and...

    Could anyone help add to my python code? I now need to calculate the mean and median. In this programming assignment you are to extend the program you wrote for Number Stats to determine the median and mode of the numbers read from the file. You are to create a program called numstat2.py that reads a series of integer numbers from a file and determines and displays the following: The name of the file. The sum of the numbers. The...

  • Don't attempt if you can't attempt fully, i will dislike a nd negative comments would be...

    Don't attempt if you can't attempt fully, i will dislike a nd negative comments would be given Please it's a request. c++ We will read a CSV files of a data dump from the GoodReads 2 web site that contains information about user-rated books (e.g., book tit le, publication year, ISBN number, average reader rating, and cover image URL). The information will be stored and some simple statistics will be calculated. Additionally, for extra credit, the program will create an...

  • Don't attempt if you can't attempt fully, i will dislike and negative comments would be given...

    Don't attempt if you can't attempt fully, i will dislike and negative comments would be given Please it's a request. c++ We will read a CSV files of a data dump from the GoodReads 2 web site that contains information about user-rated books (e.g., book titnle, publication year, ISBN number, average reader rating, and cover image URL). The information will be stored and some simple statistics will be calculated. Additionally, for extra credit, the program will create an HTML web...

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