I'm creating a temperature logger program that records date, time, and temperatures. The program should create a new .csv file that includes data and column headers. However I'm finding it difficult to add headers to the new file. I tried using two while loops, one before the other and the file didn't seem to append the headers, but recorded the data OK. Then I tried to nest in an if statement and it wrote the headers but also added them to the end of every new line of data (see picture below).
My code is as follows:
datetime1 = str(datetime.now())
#create new file with datestamp
extension = ".csv"
file_name = datetime1 + extension
file1 = open(file_name, 'a')
#add header to .csv
header = str("Date,Time,Minutes,InletTemp,ControlTemp,BedTemp,OutletTemp")
#x = 1
#while x >= 1:
# file1 = open(file_name, 'a')
# file1.write(header)
# x -= 1
#start button function
def start():
while(1):
x = 1
if x >= 1:
file1 = open(file_name, 'a')
file1.write(header)
#gather the data from each thermocouple
t1 = THERMO.getTEMP(0,1)
t2 = THERMO.getTEMP(0,2)
t3 = THERMO.getTEMP(0,3)
t4 = THERMO.getTEMP(0,4)
#themoplate LED cycle
THERMO.toggleLED(0)
#write sensor data to a file
datetime2 = datetime.now()
data = str(datetime2) + ',' + ' ' + str(t1) + ',' + str(t2) + ',' + str(t3) + ',' + str(t4)
file1 = open(file_name, 'a')
file1.write('\n')
file1.write(data)
#write sensor data to the console
print (str(datetime2))
print ('Temperature on Channel 1:',t1)
print ('Temperature on Channel 2:',t2)
print ('Temperature on Channel 3:',t3)
print ('Temperature on Channel 4:',t4)
time.sleep(1)
while loop with nested if statement:

str()function on something that's already a string.