parameters: (fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='',
              footer='', comments='# ', encoding=None)
docstring: Save an array to a text file.
  
      Parameters
      ----------
      fname : filename or file handle
          If the filename ends in ``.gz``, the file is automatically saved in
          compressed gzip format.  `loadtxt` understands gzipped files
          transparently.
      X : 1D or 2D array_like
          Data to be saved to a text file.
      fmt : str or sequence of strs, optional
          A single format (%10.5f), a sequence of formats, or a
          multi-format string, e.g. 'Iteration %d -- %10.5f', in which
          case `delimiter` is ignored. For complex `X`, the legal options
          for `fmt` are:
  
          * a single specifier, `fmt='%.4e'`, resulting in numbers formatted
            like `' (%s+%sj)' % (fmt, fmt)`
          * a full string specifying every real and imaginary part, e.g.
            `' %.4e %+.4ej %.4e %+.4ej %.4e %+.4ej'` for 3 columns
          * a list of specifiers, one per column - in this case, the real
            and imaginary part must have separate specifiers,
            e.g. `['%.3e + %.3ej', '(%.15e%+.15ej)']` for 2 columns
      delimiter : str, optional
          String or character separating columns.
      newline : str, optional
          String or character separating lines.
  
          .. versionadded:: 1.5.0
      header : str, optional
          String that will be written at the beginning of the file.
  
          .. versionadded:: 1.7.0
      footer : str, optional
          String that will be written at the end of the file.
  
          .. versionadded:: 1.7.0
      comments : str, optional
          String that will be prepended to the ``header`` and ``footer`` strings,
          to mark them as comments. Default: '# ',  as expected by e.g.
          ``numpy.loadtxt``.
  
          .. versionadded:: 1.7.0
      encoding : {None, str}, optional
          Encoding used to encode the outputfile. Does not apply to output
          streams. If the encoding is something other than 'bytes' or 'latin1'
          you will not be able to load the file in NumPy versions < 1.14. Default
          is 'latin1'.
  
          .. versionadded:: 1.14.0
  
  
      See Also
      --------
      save : Save an array to a binary file in NumPy ``.npy`` format
      savez : Save several arrays into an uncompressed ``.npz`` archive
      savez_compressed : Save several arrays into a compressed ``.npz`` archive
  
      Notes
      -----
      Further explanation of the `fmt` parameter
      (``%[flag]width[.precision]specifier``):
  
      flags:
          ``-`` : left justify
  
          ``+`` : Forces to precede result with + or -.
  
          ``0`` : Left pad the number with zeros instead of space (see width).
  
      width:
          Minimum number of characters to be printed. The value is not truncated
          if it has more characters.
  
      precision:
          - For integer specifiers (eg. ``d,i,o,x``), the minimum number of
            digits.
          - For ``e, E`` and ``f`` specifiers, the number of digits to print
            after the decimal point.
          - For ``g`` and ``G``, the maximum number of significant digits.
          - For ``s``, the maximum number of characters.
  
      specifiers:
          ``c`` : character
  
          ``d`` or ``i`` : signed decimal integer
  
          ``e`` or ``E`` : scientific notation with ``e`` or ``E``.
  
          ``f`` : decimal floating point
  
          ``g,G`` : use the shorter of ``e,E`` or ``f``
  
          ``o`` : signed octal
  
          ``s`` : string of characters
  
          ``u`` : unsigned decimal integer
  
          ``x,X`` : unsigned hexadecimal integer
  
      This explanation of ``fmt`` is not complete, for an exhaustive
      specification see [1]_.
  
      References
      ----------
      .. [1] `Format Specification Mini-Language
             <https://docs.python.org/library/string.html#format-specification-mini-language>`_,
             Python Documentation.
  
      Examples
      --------
      >>> x = y = z = np.arange(0.0,5.0,1.0)
      >>> np.savetxt('test.out', x, delimiter=',')   # X is an array
      >>> np.savetxt('test.out', (x,y,z))   # x,y,z equal sized 1D arrays
      >>> np.savetxt('test.out', x, fmt='%1.4e')   # use exponential notation
docstring_summary: Save an array to a text file.
docstring_tokens: Save an array to a text file .
function: def savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='',
              footer='', comments='# ', encoding=None):
      """
      Save an array to a text file.
  
      Parameters
      ----------
      fname : filename or file handle
          If the filename ends in ``.gz``, the file is automatically saved in
          compressed gzip format.  `loadtxt` understands gzipped files
          transparently.
      X : 1D or 2D array_like
          Data to be saved to a text file.
      fmt : str or sequence of strs, optional
          A single format (%10.5f), a sequence of formats, or a
          multi-format string, e.g. 'Iteration %d -- %10.5f', in which
          case `delimiter` is ignored. For complex `X`, the legal options
          for `fmt` are:
  
          * a single specifier, `fmt='%.4e'`, resulting in numbers formatted
            like `' (%s+%sj)' % (fmt, fmt)`
          * a full string specifying every real and imaginary part, e.g.
            `' %.4e %+.4ej %.4e %+.4ej %.4e %+.4ej'` for 3 columns
          * a list of specifiers, one per column - in this case, the real
            and imaginary part must have separate specifiers,
            e.g. `['%.3e + %.3ej', '(%.15e%+.15ej)']` for 2 columns
      delimiter : str, optional
          String or character separating columns.
      newline : str, optional
          String or character separating lines.
  
          .. versionadded:: 1.5.0
      header : str, optional
          String that will be written at the beginning of the file.
  
          .. versionadded:: 1.7.0
      footer : str, optional
          String that will be written at the end of the file.
  
          .. versionadded:: 1.7.0
      comments : str, optional
          String that will be prepended to the ``header`` and ``footer`` strings,
          to mark them as comments. Default: '# ',  as expected by e.g.
          ``numpy.loadtxt``.
  
          .. versionadded:: 1.7.0
      encoding : {None, str}, optional
          Encoding used to encode the outputfile. Does not apply to output
          streams. If the encoding is something other than 'bytes' or 'latin1'
          you will not be able to load the file in NumPy versions < 1.14. Default
          is 'latin1'.
  
          .. versionadded:: 1.14.0
  
  
      See Also
      --------
      save : Save an array to a binary file in NumPy ``.npy`` format
      savez : Save several arrays into an uncompressed ``.npz`` archive
      savez_compressed : Save several arrays into a compressed ``.npz`` archive
  
      Notes
      -----
      Further explanation of the `fmt` parameter
      (``%[flag]width[.precision]specifier``):
  
      flags:
          ``-`` : left justify
  
          ``+`` : Forces to precede result with + or -.
  
          ``0`` : Left pad the number with zeros instead of space (see width).
  
      width:
          Minimum number of characters to be printed. The value is not truncated
          if it has more characters.
  
      precision:
          - For integer specifiers (eg. ``d,i,o,x``), the minimum number of
            digits.
          - For ``e, E`` and ``f`` specifiers, the number of digits to print
            after the decimal point.
          - For ``g`` and ``G``, the maximum number of significant digits.
          - For ``s``, the maximum number of characters.
  
      specifiers:
          ``c`` : character
  
          ``d`` or ``i`` : signed decimal integer
  
          ``e`` or ``E`` : scientific notation with ``e`` or ``E``.
  
          ``f`` : decimal floating point
  
          ``g,G`` : use the shorter of ``e,E`` or ``f``
  
          ``o`` : signed octal
  
          ``s`` : string of characters
  
          ``u`` : unsigned decimal integer
  
          ``x,X`` : unsigned hexadecimal integer
  
      This explanation of ``fmt`` is not complete, for an exhaustive
      specification see [1]_.
  
      References
      ----------
      .. [1] `Format Specification Mini-Language
             <https://docs.python.org/library/string.html#format-specification-mini-language>`_,
             Python Documentation.
  
      Examples
      --------
      >>> x = y = z = np.arange(0.0,5.0,1.0)
      >>> np.savetxt('test.out', x, delimiter=',')   # X is an array
      >>> np.savetxt('test.out', (x,y,z))   # x,y,z equal sized 1D arrays
      >>> np.savetxt('test.out', x, fmt='%1.4e')   # use exponential notation
  
      """
  
      # Py3 conversions first
      if isinstance(fmt, bytes):
          fmt = asstr(fmt)
      delimiter = asstr(delimiter)
  
      class WriteWrap:
          """Convert to bytes on bytestream inputs.
  
          """
          def __init__(self, fh, encoding):
              self.fh = fh
              self.encoding = encoding
              self.do_write = self.first_write
  
          def close(self):
              self.fh.close()
  
          def write(self, v):
              self.do_write(v)
  
          def write_bytes(self, v):
              if isinstance(v, bytes):
                  self.fh.write(v)
              else:
                  self.fh.write(v.encode(self.encoding))
  
          def write_normal(self, v):
              self.fh.write(asunicode(v))
  
          def first_write(self, v):
              try:
                  self.write_normal(v)
                  self.write = self.write_normal
              except TypeError:
                  # input is probably a bytestream
                  self.write_bytes(v)
                  self.write = self.write_bytes
  
      own_fh = False
      if isinstance(fname, os_PathLike):
          fname = os_fspath(fname)
      if _is_string_like(fname):
          # datasource doesn't support creating a new file ...
          open(fname, 'wt').close()
          fh = np.lib._datasource.open(fname, 'wt', encoding=encoding)
          own_fh = True
      elif hasattr(fname, 'write'):
          # wrap to handle byte output streams
          fh = WriteWrap(fname, encoding or 'latin1')
      else:
          raise ValueError('fname must be a string or file handle')
  
      try:
          X = np.asarray(X)
  
          # Handle 1-dimensional arrays
          if X.ndim == 0 or X.ndim > 2:
              raise ValueError(
                  "Expected 1D or 2D array, got %dD array instead" % X.ndim)
          elif X.ndim == 1:
              # Common case -- 1d array of numbers
              if X.dtype.names is None:
                  X = np.atleast_2d(X).T
                  ncol = 1
  
              # Complex dtype -- each field indicates a separate column
              else:
                  ncol = len(X.dtype.names)
          else:
              ncol = X.shape[1]
  
          iscomplex_X = np.iscomplexobj(X)
          # `fmt` can be a string with multiple insertion points or a
          # list of formats.  E.g. '%10.5f\t%10d' or ('%10.5f', '$10d')
          if type(fmt) in (list, tuple):
              if len(fmt) != ncol:
                  raise AttributeError('fmt has wrong shape.  %s' % str(fmt))
              format = asstr(delimiter).join(map(asstr, fmt))
          elif isinstance(fmt, str):
              n_fmt_chars = fmt.count('%')
              error = ValueError('fmt has wrong number of %% formats:  %s' % fmt)
              if n_fmt_chars == 1:
                  if iscomplex_X:
                      fmt = [' (%s+%sj)' % (fmt, fmt), ] * ncol
                  else:
                      fmt = [fmt, ] * ncol
                  format = delimiter.join(fmt)
              elif iscomplex_X and n_fmt_chars != (2 * ncol):
                  raise error
              elif ((not iscomplex_X) and n_fmt_chars != ncol):
                  raise error
              else:
                  format = fmt
          else:
              raise ValueError('invalid fmt: %r' % (fmt,))
  
          if len(header) > 0:
              header = header.replace('\n', '\n' + comments)
              fh.write(comments + header + newline)
          if iscomplex_X:
              for row in X:
                  row2 = []
                  for number in row:
                      row2.append(number.real)
                      row2.append(number.imag)
                  s = format % tuple(row2) + newline
                  fh.write(s.replace('+-', '-'))
          else:
              for row in X:
                  try:
                      v = format % tuple(row) + newline
                  except TypeError as e:
                      raise TypeError("Mismatch between array dtype ('%s') and "
                                      "format specifier ('%s')"
                                      % (str(X.dtype), format)) from e
                  fh.write(v)
  
          if len(footer) > 0:
              footer = footer.replace('\n', '\n' + comments)
              fh.write(comments + footer + newline)
      finally:
          if own_fh:
              fh.close()
function_tokens: def savetxt ( fname , X , fmt = '%.18e' , delimiter = ' ' , newline = '\n' , header = '' , footer = '' , comments = '# ' , encoding = None ) : # Py3 conversions first if isinstance ( fmt , bytes ) : fmt = asstr ( fmt ) delimiter = asstr ( delimiter ) class WriteWrap : """Convert to bytes on bytestream inputs.
  
          """ def __init__ ( self , fh , encoding ) : self . fh = fh self . encoding = encoding self . do_write = self . first_write def close ( self ) : self . fh . close ( ) def write ( self , v ) : self . do_write ( v ) def write_bytes ( self , v ) : if isinstance ( v , bytes ) : self . fh . write ( v ) else : self . fh . write ( v . encode ( self . encoding ) ) def write_normal ( self , v ) : self . fh . write ( asunicode ( v ) ) def first_write ( self , v ) : try : self . write_normal ( v ) self . write = self . write_normal except TypeError : # input is probably a bytestream self . write_bytes ( v ) self . write = self . write_bytes own_fh = False if isinstance ( fname , os_PathLike ) : fname = os_fspath ( fname ) if _is_string_like ( fname ) : # datasource doesn't support creating a new file ... open ( fname , 'wt' ) . close ( ) fh = np . lib . _datasource . open ( fname , 'wt' , encoding = encoding ) own_fh = True elif hasattr ( fname , 'write' ) : # wrap to handle byte output streams fh = WriteWrap ( fname , encoding or 'latin1' ) else : raise ValueError ( 'fname must be a string or file handle' ) try : X = np . asarray ( X ) # Handle 1-dimensional arrays if X . ndim == 0 or X . ndim > 2 : raise ValueError ( "Expected 1D or 2D array, got %dD array instead" % X . ndim ) elif X . ndim == 1 : # Common case -- 1d array of numbers if X . dtype . names is None : X = np . atleast_2d ( X ) . T ncol = 1 # Complex dtype -- each field indicates a separate column else : ncol = len ( X . dtype . names ) else : ncol = X . shape [ 1 ] iscomplex_X = np . iscomplexobj ( X ) # `fmt` can be a string with multiple insertion points or a # list of formats.  E.g. '%10.5f\t%10d' or ('%10.5f', '$10d') if type ( fmt ) in ( list , tuple ) : if len ( fmt ) != ncol : raise AttributeError ( 'fmt has wrong shape.  %s' % str ( fmt ) ) format = asstr ( delimiter ) . join ( map ( asstr , fmt ) ) elif isinstance ( fmt , str ) : n_fmt_chars = fmt . count ( '%' ) error = ValueError ( 'fmt has wrong number of %% formats:  %s' % fmt ) if n_fmt_chars == 1 : if iscomplex_X : fmt = [ ' (%s+%sj)' % ( fmt , fmt ) , ] * ncol else : fmt = [ fmt , ] * ncol format = delimiter . join ( fmt ) elif iscomplex_X and n_fmt_chars != ( 2 * ncol ) : raise error elif ( ( not iscomplex_X ) and n_fmt_chars != ncol ) : raise error else : format = fmt else : raise ValueError ( 'invalid fmt: %r' % ( fmt , ) ) if len ( header ) > 0 : header = header . replace ( '\n' , '\n' + comments ) fh . write ( comments + header + newline ) if iscomplex_X : for row in X : row2 = [ ] for number in row : row2 . append ( number . real ) row2 . append ( number . imag ) s = format % tuple ( row2 ) + newline fh . write ( s . replace ( '+-' , '-' ) ) else : for row in X : try : v = format % tuple ( row ) + newline except TypeError as e : raise TypeError ( "Mismatch between array dtype ('%s') and " "format specifier ('%s')" % ( str ( X . dtype ) , format ) ) from e fh . write ( v ) if len ( footer ) > 0 : footer = footer . replace ( '\n' , '\n' + comments ) fh . write ( comments + footer + newline ) finally : if own_fh : fh . close ( )