Write a family to a csv file.

    :type family: :class:`eqcorrscan.core.match_filter.Family`
    :param family: Family to write to file
    :type filename: str
    :param filename: File to write to.
19597
def _write_family(family, filename):
    
    with open(filename, 'w') as f:
        for detection in family.detections:
            det_str = ''
            for key in detection.__dict__.keys():
                if key == 'event' and detection.__dict__[key] is not None:
                    value = str(detection.event.resource_id)
                elif key in ['threshold', 'detect_val', 'threshold_input']:
                    value = format(detection.__dict__[key], '.32f').rstrip('0')
                else:
                    value = str(detection.__dict__[key])
                det_str += key + ': ' + value + '; '
            f.write(det_str + '\n')
    return
926894
def write_csv(data, file_name, encoding='utf-8'):
    '''
    
    '''
    name_extension = len(data) > 1
    root, ext = os.path.splitext(file_name)

    for i, sheet in enumerate(data):
        fname = file_name if not name_extension else root+"_"+str(i)+ext
        with open(fname, 'wb') as date_file:
            csv_file = csv.writer(date_file, encoding=encoding)
            for line in sheet:
                csv_file.writerow(line)
828893
def _save(self):
        
        # if not first time saving, copy .csv to a backup
        if os.path.isfile(self._full_filename):
            shutil.copyfile(self._full_filename, self._full_backup_filename)

        # write to csv
        with open(self._full_filename, 'w') as file:
            writer = csv.DictWriter(file, fieldnames=self._headers)
            writer.writeheader()
            for row in self._table:
                writer.writerow(row)
1210706
def write(self, filename):
        """"""
        if file_exists(filename):
            return filename
        out_files = [filename, filename + ".rownames", filename + ".colnames"]
        with file_transaction(out_files) as tx_out_files:
            with open(tx_out_files[0], "wb") as out_handle:
                scipy.io.mmwrite(out_handle, scipy.sparse.csr_matrix(self.matrix))
            pd.Series(self.rownames).to_csv(tx_out_files[1], index=False)
            pd.Series(self.colnames).to_csv(tx_out_files[2], index=False)
        return filename
734416
def _write_segments(self, filename):
        
        # Column headers
        shead = '\t'.join(['id', 'multiplicon', 'genome', 'list', 'first',
                           'last', 'order'])
        with open(filename, 'w') as fhandle:
            fhandle.write(shead + '\n')
            for mrow in self.segments:
                fhandle.write('\t'.join([str(e) for e in mrow]) + '\n')
417690
def write_csv(fileobj, rows, encoding=ENCODING, dialect=DIALECT):
    """"""
    csvwriter = csv.writer(fileobj, dialect=dialect)
    csv_writerows(csvwriter, rows, encoding)
1284668
def write_csv_files(args, infilenames, outfilename):
    
    def csv_convert(line):
        """Strip punctuation and insert commas"""
        clean_line = []
        for word in line.split(' '):
            clean_line.append(word.strip(string.punctuation))
        return ', '.join(clean_line)

    if not outfilename.endswith('.csv'):
        outfilename = outfilename + '.csv'
    outfilename = overwrite_file_check(args, outfilename)

    all_text = []  # Text must be aggregated if writing to a single output file
    for i, infilename in enumerate(infilenames):
        parsed_text = get_parsed_text(args, infilename)
        if parsed_text:
            if args['multiple']:
                if not args['quiet']:
                    print('Attempting to write to {0}.'.format(outfilename))

                csv_text = [csv_convert(x) for x in parsed_text]
                print(csv_text)
                write_file(csv_text, outfilename)
            elif args['single']:
                all_text += parsed_text
                # Newline added between multiple files being aggregated
                if len(infilenames) > 1 and i < len(infilenames) - 1:
                    all_text.append('\n')

    # Write all text to a single output file
    if args['single'] and all_text:
        if not args['quiet']:
            print('Attempting to write {0} page(s) to {1}.'
                  .format(len(infilenames), outfilename))

        csv_text = [csv_convert(x) for x in all_text]
        print(csv_text)
        write_file(csv_text, outfilename)
541576
def write(self, filename, header=None):
        

        origfile = self._filename

        try:
            with open(filename, 'w') as _file:
                self.writestream(_file, header)
                self._filename = filename
            return True

        except IOError:
            self._filename = origfile
            return False
176275
def writefile(filename, content):
    
    with open(path_expand(filename), 'w') as outfile:
        outfile.write(content)
588369
def simple_write(filename, group, times, features,
                 properties=None, item='item', mode='a'):
    """"""
    write(filename, group, [item], [times], [features], mode=mode,
          properties=[properties] if properties is not None else None)
1019693
def write(self, file_or_filename):
        
        if isinstance(file_or_filename, basestring):
            file = None
            try:
                file = open(file_or_filename, "wb")
            except Exception, detail:
                logger.error("Error opening %s." % detail)
            finally:
                if file is not None:
                    self._write_data(file)
                    file.close()
        else:
            file = file_or_filename
            self._write_data(file)

        return file
475817
def output(self, filename):
        
        info = 'Inheritance\n'

        if not self.contracts:
            return

        info += blue('Child_Contract -> ') + green('Immediate_Base_Contracts')
        info += green(' [Not_Immediate_Base_Contracts]')
        for child in self.contracts:
            info += blue(f'\n+ {child.name}')
            if child.inheritance:
                immediate = child.immediate_inheritance
                not_immediate = [i for i in child.inheritance if i not in immediate]
                info += ' -> ' + green(", ".join(map(str, immediate)))
                if not_immediate:
                    info += ", ["+ green(", ".join(map(str, not_immediate))) + "]"

        info += green('\n\nBase_Contract -> ') + blue('Immediate_Child_Contracts')
        info += blue(' [Not_Immediate_Child_Contracts]')
        for base in self.contracts:
            info += green(f'\n+ {base.name}')
            children = list(self._get_child_contracts(base))
            if children:
                immediate = [child for child in children if base in child.immediate_inheritance]
                not_immediate = [child for child in children if not child in immediate]
                info += ' -> ' + blue(", ".join(map(str, immediate)))
                if not_immediate:
                    info += ', [' + blue(", ".join(map(str, not_immediate))) + ']'
        self.info(info)
419257
def _write_to_file(self, filename, bytesvalue):
        """"""
        fh, tmp = tempfile.mkstemp()
        with os.fdopen(fh, self._flag) as f:
            f.write(self._dumps(bytesvalue))
        rename(tmp, filename)
        os.chmod(filename, self._mode)
1341439
def write_updates_to_csv(self, updates):
        
        with open(self._csv_file_name, 'w') as csvfile:
            csvwriter = self.csv_writer(csvfile)
            csvwriter.writerow(CSV_COLUMN_HEADERS)

            for update in updates:
                row = [
                    update.name,
                    update.current_version,
                    update.new_version,
                    update.prelease,
                ]
                csvwriter.writerow(row)
1060706
@VisibleForTesting
  public static void writeCSVFile(Collection<? extends PropertyKey> defaultKeys, String filePath)
      throws IOException {
    if (defaultKeys.size() == 0) {
      return;
    }

    FileWriter fileWriter;
    Closer closer = Closer.create();
    String[] fileNames = {"user-configuration.csv", "master-configuration.csv",
        "worker-configuration.csv", "security-configuration.csv",
        "common-configuration.csv", "cluster-management-configuration.csv"};

    try {
      // HashMap for FileWriter per each category
      Map<String, FileWriter> fileWriterMap = new HashMap<>();
      for (String fileName : fileNames) {
        fileWriter = new FileWriter(PathUtils.concatPath(filePath, fileName));
        // Write the CSV file header and line separator after the header
        fileWriter.append(CSV_FILE_HEADER + "\n");
        //put fileWriter
        String key = fileName.substring(0, fileName.indexOf("configuration") - 1);
        fileWriterMap.put(key, fileWriter);
        //register file writer
        closer.register(fileWriter);
      }

      // Sort defaultKeys
      List<PropertyKey> dfkeys = new ArrayList<>(defaultKeys);
      Collections.sort(dfkeys);

      for (PropertyKey propertyKey : dfkeys) {
        String pKey = propertyKey.toString();
        String defaultDescription;
        if (propertyKey.getDefaultSupplier().get() == null) {
          defaultDescription = "";
        } else {
          defaultDescription = propertyKey.getDefaultSupplier().getDescription();
        }
        // Quote the whole description to escape characters such as commas.
        defaultDescription = String.format("\"%s\"", defaultDescription);

        // Write property key and default value to CSV
        String keyValueStr = pKey + "," + defaultDescription + "\n";
        if (pKey.startsWith("alluxio.user.")) {
          fileWriter = fileWriterMap.get("user");
        } else if (pKey.startsWith("alluxio.master.")) {
          fileWriter = fileWriterMap.get("master");
        } else if (pKey.startsWith("alluxio.worker.")) {
          fileWriter = fileWriterMap.get("worker");
        } else if (pKey.startsWith("alluxio.security.")) {
          fileWriter = fileWriterMap.get("security");
        } else if (pKey.startsWith("alluxio.keyvalue.")) {
          fileWriter = fileWriterMap.get("key-value");
        } else if (pKey.startsWith("alluxio.integration")) {
          fileWriter = fileWriterMap.get("cluster-management");
        } else {
          fileWriter = fileWriterMap.get("common");
        }
        fileWriter.append(keyValueStr);
      }

      LOG.info("Property Key CSV files were created successfully.");
    } catch (Exception e) {
      throw closer.rethrow(e);
    } finally {
      try {
        closer.close();
      } catch (IOException e) {
        LOG.error("Error while flushing/closing Property Key CSV FileWriter", e);
      }
    }
  }
1259972
def serialize(self):
        
        lines = []

        for criterion in self.filter_criteria:
            lines.append(criterion.name())
            lines.append(criterion.serialize())

        return '\n'.join(lines)
1218220
def to_csv(self, filename: str, latexify_names: bool = False):
        

        elements = set()
        for entry in self.entries:
            elements.update(entry.composition.elements)
        elements = sorted(list(elements), key=lambda a: a.X)
        writer = csv.writer(open(filename, "w"), delimiter=unicode2str(","),
                            quotechar=unicode2str("\""),
                            quoting=csv.QUOTE_MINIMAL)
        writer.writerow(["Name"] + elements + ["Energy"])
        for entry in self.entries:
            row = [entry.name if not latexify_names
                   else re.sub(r"([0-9]+)", r"_{\1}", entry.name)]
            row.extend([entry.composition[el] for el in elements])
            row.append(entry.energy)
            writer.writerow(row)