-Change the code below (IN PYTHON) so the names and grades will be written to on
ID: 3915572 • Letter: #
Question
-Change the code below (IN PYTHON) so the names and grades will be written to one csv file, but the names and grades should be in two different lists in the code. Then use a loop to write out the csv file.
Hints:
#create the two lists (hard coded) with the same values.
x = len(namesList) # both lists have the same length.
csvWriter.writerow( [“Name”, “Grade”] )
for i in range(x): #remember that i is a number not a value
csvWriter.writerow ( [… , …] )
So, read the two lists, extracting the name and grade. And in a print statement, print out something like what is shown below. Make sure that everything lines up using the % format.
Mary 95
Joe 87
Sam 97
CODE GIVEN (IN PYTHON):
import csv
def main():
outfile = open("grades.csv","w", newline="")
csvWriter = csv.writer(outfile, lineterminator=' ')
name1 = "Mary"
grade1 = 95
name2 = "Joe"
grade2 = 87
name3 = "Sam"
grade3 = 97
# must use a list to write
csvWriter.writerow( ["Name","Grade"] )
csvWriter.writerow( [name1,grade1])
csvWriter.writerow( [name2,grade2] )
csvWriter.writerow( [name3,grade3] )
outfile.close()
main()
THANK YOU IN ADVANCE!
Explanation / Answer
import csv def main(): outfile = open("grades.csv", "w", newline="") csvWriter = csv.writer(outfile, lineterminator=' ') # must use a list to write names = ["Mary", "Joe", "Sam"] grades = [95, 87, 97] csvWriter.writerow(["Name", "Grade"]) for i in range(len(names)): csvWriter.writerow([names[i], grades[i]]) outfile.close() main()
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.