Skip to content
Advertisement

Python – Write array output in .csv file for each for loop iteration

I’m trying to write the output data of this for loop in a .csv file. However, what gets written in the .csv file with the current code is the data of a single iteration. I want to append and write the data in a new row for each iteration. How do I do that?

    for i in range(0,8):
#    for j in range (0,2):
    gyro_xy_orth = (np.dot(H[i,:], xy_orth)/np.square(xy_norm))*xy_orth
    gyro_xy = H[i,:] - gyro_xy_orth
    gyro_xz_orth = (np.dot(H[i,:], xz_orth)/np.square(xz_norm))*xz_orth
    gyro_xz = H[i,:] - gyro_xz_orth
    gyro_yz_orth = (np.dot(H[i,:], yz_orth)/np.square(yz_norm))*yz_orth
    gyro_yz = H[i,:] - gyro_yz_orth

    gyro_xy_m_orth = (np.dot(H[i,:], xy_m_orth)/np.square(xy_norm))*xy_m_orth
    gyro_xy_m = H[i,:] - gyro_xy_m_orth
    gyro_xz_m_orth = (np.dot(H[i,:], xz_m_orth)/np.square(xz_norm))*xz_m_orth
    gyro_xz_m = H[i,:] - gyro_xz_m_orth
    gyro_yz_m_orth = (np.dot(H[i,:], yz_m_orth)/np.square(yz_norm))*yz_m_orth
    gyro_yz_m = H[i,:] - gyro_yz_m_orth

    gyro_projections = [gyro_xy, gyro_xz, gyro_yz, gyro_xy_m, gyro_xz_m, gyro_yz_m]
    #print("Projection of gyro ", i+1, " on planes xyz: ", gyro_projections)

    with open('/Users/path/gyro_config.csv', 'w', newline='') as f:
        writer = csv.writer(f, delimiter=',')
        writer.writerows(gyro_projections)

Advertisement

Answer

Try to append instead of write mode:

with open('/Users/emanalawadhi/Documents/MBRSCWork/TASKSWork/SSDD/MBZsat/GYRO/gyro_config.csv', 'a', newline='') as f:
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement