'Not able to store data in a CSV file with a while loop

I have problem to store data in a CSV file in Python. I am taking measurement from two different instruments and I want to store them in a CSV file. It is measuring continuously and I want to stop the measurement anytime with a key stroke.

My problem is that I only get a the header plus the first measurement and that's it. It is not looping and I don't understand why.

Here is the code:

data = []
stored_exception = None
file_name = ("Logger_")+str(time.strftime("%Y_%B_%d_%H_%M_%S"))+(".csv")
client = init_MKS(SERVER_HOST, SERVER_PORT)
scope = init_MSO()

# create a CSV file with header
write_CSV_file(file_name, 'w', HEADER)
print('------- Measurement started -------')
print('To stop the measurement press Ctrl+C\n')
try:    
    while True:
        valuesMKS = logger_MKS(client)
        valuesMSO = logger_MSO(scope)
        data.extend(valuesMSO)
        data.extend(valuesMKS)
        write_CSV_file(file_name, 'a', data)
        time.sleep(1) # Do not need all the data point
# Press Ctrl+C to stop the programm
except KeyboardInterrupt:
    print('------- Measurement stopped -------')
# Cheching errors of communications with MSO44
except visa.VisaIOError:
    print('ERROR!\nConnection lost')
    print('------- Measurement stopped -------\n')

logger_MKS uses a Modbus protocole and logger_MSO a LabVIEW visa protocol. Here is the function I created to create or store the data:

def write_CSV_file(file, mode_file, data):
    with open(file, mode=mode_file,  newline='') as backup_file:
        writer_file = csv.writer(backup_file, delimiter=';')
        writer_file.writerow(data)
        backup_file.close()

I know it is not the best way open and close continuously a CSV I am not a computer science engineer and it the safest way to be sure the data are stored somewhere is the computer shuts down (it happens sometimes)

Many thanks for your help



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source