Пример #1
0
def test_format_header():
    r"""Test formatting header."""
    kws_all = dict(
        field_names=['name', 'number', 'value', 'complex'],
        field_units=['n/a', 'g', 'cm', 'n/a'])
    res_all = dict(
        names="# name\tnumber\tvalue\tcomplex\n",
        units="# n/a\tg\tcm\tn/a\n")
    if platform._is_win:  # pragma: windows
        kws_all['format_str'] = "%5s\t%l64d\t%g\t%g%+gj\n"
        res_all['format'] = "# " + kws_all['format_str']
    else:
        kws_all['format_str'] = "%5s\t%ld\t%g\t%g%+gj\n"
        res_all['format'] = "# " + kws_all['format_str']
    kws_all['dtype'] = serialize.cformat2nptype(kws_all['format_str'],
                                                names=kws_all['field_names'])
    for x in [kws_all, res_all]:
        for k, v in x.items():
            if isinstance(v, str):
                x[k] = backwards.unicode2bytes(v)
            elif isinstance(v, list):
                x[k] = [backwards.unicode2bytes(iv) for iv in v]
    test_list = [(['format_str', 'field_names', 'field_units'],
                  ['names', 'units', 'format']),
                 (['field_names', 'field_units', 'dtype'],
                  ['names', 'units', 'format']),
                 (['field_units', 'dtype'],
                  ['names', 'units', 'format']),
                 (['field_names'], ['names']),
                 (['field_units'], ['units'])]
    for kws_keys, res_keys in test_list:
        kws = {k: kws_all[k] for k in kws_keys}
        res = backwards.unicode2bytes('').join([res_all[k] for k in res_keys])
        nt.assert_equal(serialize.format_header(**kws), res)
    nt.assert_raises(ValueError, serialize.format_header)
Пример #2
0
 def write_header(self):
     r"""Write header lines to the file based on the serializer info."""
     if self.header_was_written:
         return
     header_msg = serialize.format_header(
         format_str=self.serializer.format_str,
         field_names=self.serializer.field_names,
         field_units=self.serializer.field_units,
         comment=self.comment,
         newline=self.newline,
         delimiter=self.delimiter)
     self.fd.write(header_msg)
     self.header_was_written = True
Пример #3
0
    def write_table(self, fname):
        r"""Write the table out to a file.

        Args:
            fname (str): Full path to the file that the table should be
                written to.

        """
        header = serialize.format_header(format_str=self.fmt_str,
                                         comment=self.comment,
                                         delimiter=self.delimiter,
                                         newline=self.newline,
                                         field_names=self.field_names,
                                         field_units=self.field_units)
        body = serialize.array_to_table(self.file_array, self.fmt_str)
        with open(fname, 'wb') as fd:
            fd.write(header)
            fd.write(body)
Пример #4
0
    def write_array(self, array, names=None, skip_header=False):
        r"""Write a numpy array to the table.

        Args:
            array (np.ndarray): Array to be written.
            names (list, optional): List of column names to write out. If
                not provided, existing names are used if they exist. Defaults
                to None.
            skip_header (bool, optional): If True, no header information is
                written (it is assumed it was already written. Defaults to
                False.

        Raises:
            ValueError: If names are provided, but not the same number as
                there are columns.

        """
        openned = False
        fd = self.fd
        if not self.is_open:
            fd = open(self.filepath, self.open_mode)
            openned = True
        # Write header
        if not skip_header:
            if names is None:
                names = self.column_names
            header = serialize.format_header(format_str=self.format_str,
                                             comment=self.comment,
                                             delimiter=self.column,
                                             newline=self.newline,
                                             field_names=names)
            fd.write(header)
        # Write array
        fd.write(
            serialize.array_to_table(array,
                                     self.format_str,
                                     use_astropy=self.use_astropy))
        if openned:
            fd.close()
            fd = None