title: How to save an updated fits file with headers in correct places?
body: <p>I want to edit the data in my fits file using astropy and then save it to its original file. Below is my code and the error message, please ignore if there's a redundant line because obviously I opened the file twice but I still get the error after deleting it.</p>
  <pre><code>file_list = sorted(glob.glob('*.fits'))    #read in my three fits files
  hdudata = np.full((3,720,1440), 0)         # a test list to store the data
  
  for im in range(len(file_list)):
      hdu_list = fits.open(file_list[im])
      hdudata[im] = hdu_list[0].data    # read in the data from fits file
      if im == 2:                       # I only want to change the last image
          with fits.open(file_list[im], mode='update') as hdus:
              hdu = hdus[0]
              hdu.data = (hdudata[im-1] + hdudata[im])/2.    # basically add two images
                                                             # and take the average
              hdu.close()    # this is required otherwise an error message pops up saying
                                  # the next line cannot proceed as the file is being run
              hdu.flush()         # the error line
  
  
  VerifyError: 
  Verification reported errors:
  HDU 0:
      'NAXIS1' card at the wrong place (card 4).
      'NAXIS2' card at the wrong place (card 5).
      'EXTEND' card at the wrong place (card 6).
  Note: astropy.io.fits uses zero-based indexing.
  </code></pre>
  <p>I have only accessed and changed the data but why is the error taking place in my header, I met no problem reading the headers (though I didn't include in this code above) then why is it faulty when saving it?</p>