Question

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 not a string. This means you do not need the with..as nor create the csv reader in your function, but this will be done in the code calling your function. For example, to execute read_csv_header using a file named "smallDataFile.csv" you would write the following code:
with open("smallDataFile.csv") as f_in:
csv_r = csv.reader(f_in)
header = read_csv_header(csv_r)

You would then want to include code to check that header had the expected value.

For example, suppose the first line of the file being read by csv_r was:

tow_date,tow_reason

then the call read_csv_header(csv_r) would need to return:

['tow_date','tow_reason']

read_data

Define a function named read_data with two parameters. The first parameter will be a csv reader object (e.g., the value returned when calling the function csv.reader) and the second parameter will be a list of strings representing the keys for this data. The list matches the order of data in the file, so the second parameter's first entry is the key to use for data in the file's first column, the second parameter's second entry is the key to use for data in the file's second column, and so on.

The function's first parameter will be a csv reader object and not a string. This means you do not need the with..as nor create the csv reader in your function, but this will be done in the code calling your function. For example, to execute read_data using a file named "smallDataFileWithoutHeaders.csv" you would write the following code:
with open("smallDataFileWithoutHeaders.csv") as f_in:
csv_r = csv.reader(f_in)
result = read_data(csv_r,['tow_date','tow_reason'])

You would then want to include code to check that header had the expected value.

The function should return a list of dictionaries. This list will contain a dictionary for each row read using the first parameter. The keys of these dictionaries will be the entries in the second parameter and the values will be the data read in from the file (you can assume there will be equal numbers list entries and columns).



For example, suppose the lines of the file being read by csv_r were:

2015-12-30,IL

2018-04-07,GA

then the call read_data(csv_r,['tow_date','tow_reason']) would need to return:

[{'tow_date': '2015-12-30', 'tow_reason': 'IL'},
{'tow_date': '2018-04-07', 'tow_reason': 'GA'}]

write_csv_header

Define a function named write_csv_header with two parameters. The first parameter will be a csv writer object (e.g., the value returned when calling the function csv.writer) and the second parameter will be a dictionary. Your function must use the first parameter to write the dictionary's keys as a row. The list of keys written out must then be returned.

The function's first parameter will be a csv writer object and not a string. This means you do not need the with..as nor create the csv writer in your function, but this will be done in the code calling your function. For example, to execute write_csv_header using a file named "smallDataFileIWrote.csv" you would write the following code:
with open("smallDataFileIWrote.csv",'w') as f_out:
csv_w = csv.writer(f_out)
result = write_csv_header(csv_w,{'td':'2020', 'tr': 'AB'})

You would then want to include code to check that result variable and file that you wrote each had the expected value.

For example, if csv_w were assigned to a csv writer object, then the call:
write_csv_header(csv_w, {'tow_date': '2020-01-20', 'tow_reason': 'AB'})
would need to write a line to the file like:
tow_date, tow_reason
and would need to return:
['tow_reason', 'tow_reason']

write_dictionaries_to_csv

Define a function named write_dictionaries_to_csv with three parameters. The first parameter will be a csv writer object (e.g., the value returned when calling the function csv.writer), the second parameter will be a list of dictionaries, and the third parameter will be a list of keys. You may assume that each key in the third parameter exists as a key in each of the dictionaries in the second parameter.

The function's first parameter will be a csv writer object and not a string. This means you do not need the with..as nor create the csv writer in your function, but this will be done in the code calling your function. For example, to execute write_dictionaries_to_csv using a file named "smallDataFileIWrote.csv" you would write the following code:
with open("smallDataFileIWrote.csv",'w') as f_out:
csv_w = csv.writer(f_out)
write_dictionaries_to_csv(csv_w,{'td':'2020', 'tr': 'AB'})

You would then want to include code to check that the file that you wrote each had the expected value.

Your function must write the values from each dictionary as a row in the CSV file. The order of the values in the row must correspond to the order of the keys in the third argument.

For example, if
data = [{'tow_reason': 'IL', 'tow_date': '2013-06-18'},
{'tow_date': '2014-09-25', 'tow_reason': 'GA'}]
and csv_w were assigned to a csv writer object, then the call:

write_dictionaries_to_csv(csv_w, data,['tow_reason','tow_date'])

would append the following two rows to the file being written to using csv_w:
IL, 2013-06-18

GA, 2014-09-25

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

import csv
#function to read header from a csv file
def read_csv_header(csv_r):
   #header is the first row in csv file
   for row in csv_r:
       return row
#function to read data from csv file into a dictionary
def read_data(csv_r, header):
   #data is a list of dictionaries
   data = []
   #for every row in csv file
   for row in csv_r:
       temp = {}
       #create dictionary
       for i in range(len(header)):
           temp[header[i]] = row[i]
       #add the dictionary to data
       data.append(temp)
   return data
#function to srite header into a csv file
def write_csv_header(csv_w, data):
   #take the keys in data
   output = list(data.keys())
   #write keys of data in csv file
   csv_w.writerow(output)
   return output
#write the dictionaries into csv file
def write_dictionaries_to_csv(csv_w, data, header):
   #write the header
   csv_w.writerow(header)
   #for every row in data
   for row in data:
       temp = []
       #create a list
       for key in header:
           temp.append(row[key])
       #write the list in csv file
       csv_w.writerow(temp)
#this code will check read_csv_header function
with open("smallDataFile.csv") as f_in:
   csv_r = csv.reader(f_in)
   header = read_csv_header(csv_r)
   print(header)
#this code will check read_data function
with open("smallDataFileWithoutHeaders.csv") as f_in:
   csv_r = csv.reader(f_in)
   result = read_data(csv_r,['tow_date','tow_reason'])
   print(result)
#this code will check write_csv_header function
with open("smallDataFileIWrote.csv",'w') as f_out:
   csv_w = csv.writer(f_out)
   result = write_csv_header(csv_w, {'tow_date': '2020-01-20', 'tow_reason': 'AB'})
   print(result)
#this code will check write-dictionaries_to_csv function
with open("smallDataFileIWrote.csv",'w') as f_out:
   csv_w = csv.writer(f_out)
   data = [{'tow_reason': 'IL', 'tow_date': '2013-06-18'},{'tow_date': '2014-09-25', 'tow_reason': 'GA'}]
   write_dictionaries_to_csv(csv_w, data,['tow_reason','tow_date'])

Folloew the images for indentation.

If you have any doubts please comment and please don't dislike.

Add a comment
Know the answer?
Add Answer to:
Functionality to build (4 functions) read_csv_header Define a function named read_csv_header with one parameter. This parameter...
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
  • Define a Python function named borough_count that has one parameter. The parameter is a string representing...

    Define a Python function named borough_count that has one parameter. The parameter is a string representing the name of a CSV file. The CSV file is a subset of NYC's dataset of all film permits issued since April 2016. Each row in the CSV file has the format: Event Id, Police Precinct(s), Event Type, Borough, Category Your function must return a dictionary. The keys of this dictionary will be the boroughs read in from the file (boroughs are at index...

  • PYTHON Hello can someone create the following functions? I'm not sure how to start on them....

    PYTHON Hello can someone create the following functions? I'm not sure how to start on them. makeDictionary Define a function named makeDictionary with two parameters. The first argument passed the function must be a list of strings to be used as keys, while the second is a list of the same length containing values (of some type). This function must return a dictionary consisting of the keys paired with the corresponding values. For example, makeDictionary(['apno','value'],['REP-12','450']) must return this dictionary: {'apno':...

  • Python function: This is my code and I don't know how to add the column to...

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

  • Python 5. Write a function named grade_components that has one parameter, a dictionary. The keys for...

    Python 5. Write a function named grade_components that has one parameter, a dictionary. The keys for the dictionary are strings and the values are lists of numbers. The function should create a new dictionary where the keys are the same strings as the original dictionary and the values are tuples. The first entry in each tuple should be the weighted average of the non-negative values in the list (where the weight was the number in the 0 position of the...

  • 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 this problem, assume salesperson data are stored in a database table named staff. Also assume the columns in the table are named name, carsSold, and totalSales Write a Python function named ge...

    For this problem, assume salesperson data are stored in a database table named staff. Also assume the columns in the table are named name, carsSold, and totalSales Write a Python function named getSalesSortedByNames. Your function will have 2 parameters. The first parameter is a database cursor and the second parameter is a float. Your function should start by retrieving those rows in the staff table whose totalsales field is equal to the second parameter. (The next paragraph shows the Python...

  • Define a JavaScript function named showScores which has one parameter which is a JSON blob (JSON...

    Define a JavaScript function named showScores which has one parameter which is a JSON blob (JSON encoding). The parameter encodes an object which maps strings to Numbers. This object will have the keys: "total" and "count". Your function should display the parameter's value associated with "total" in a div element whose id is "overall" . It must also display the parameter's value associated with "count" in a div element whose id is "num".

  • Create a JavaScript function named display_data that has two parameters. The first parameter will be a...

    Create a JavaScript function named display_data that has two parameters. The first parameter will be a String containing a JSON blob like the function in part 1 returns. The second parameter will be a boolean. Start by using the JSON library to convert the first parameter into a usable JavaScript Object. Next get the HTML element whose id is "data". This HTML element is a div. If the second parameter is equal to true ​, write the value associated with...

  • In Python, having trouble writing this function. Define a function named makeDictionary with two parameters. The...

    In Python, having trouble writing this function. Define a function named makeDictionary with two parameters. The first argument passed the function must be a list of strings to be used as keys, while the second is a list of the same length containing values (of some type). This function must return a dictionary consisting of the keys paired with the corresponding values. Help would be appreciated

  • In this problem, you should write one function named copy and increment. This function will have...

    In this problem, you should write one function named copy and increment. This function will have one parameter, which you can assume will be a list of integers. This function should return a copy of the parameter list, in which each number from the parameter list has been increased by 1. The function should not modify the values in the parameter list. For example, the code: values - 20, 40, 10, 60, 77, 2) other copy and incrementales) print values...

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