I'm trying to build a csv file one row at a time by appending to an existing file in a loop. I also want to have column headers at the top of the file. Is there a way to have the headers while building the file by appending.
This is my code:
while True:
try:
print("What class are you from? Between 1 to 3. ") # this is deciding which class the user is from
Class = int(input()) #depending on the input, it goes to the correct class files to be stored as a CSV file
if Class == 1:
with open('Class 1.csv', 'a') as csvfile:
fieldnames = ['Name', 'Score']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames) #this is for writing the headers
writer.writeheader()
writer.writerow({'Name': name, 'Score': score})
break #this is to get out of the loop
elif Class == 2:
with open('Class 2.csv', 'a') as csvfile:
fieldnames = ['Name', 'Score']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'Name': name, 'Score': score})
break
elif Class == 3:
with open('Class 3.csv', 'a') as csvfile:
fieldnames = ['Name', 'Score']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'Name': name, 'Score': score})
break
else:
print("Please enter a number between 1 to 3.") #this loops if the user inputs a number too high
except ValueError:
print("Please enter a number between 1 to 3.")