<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def to(self, fmt=None, filename=None):
 """ Outputs the molecule to a file or string. Args: fmt (str):
 Format to output to. Defaults to JSON unless filename is provided. If fmt is specifies, it overrides whatever the filename is. Options include "xyz", "gjf", "g03", "json". If you have OpenBabel installed, any of the formats supported by OpenBabel. Non-case sensitive. filename (str):
 If provided, output will be written to a file. If fmt is not specified, the format is determined from the filename. Defaults is None, i.e. string output. Returns: (str) if filename is None. None otherwise. """

        from pymatgen.io.xyz import XYZ
        from pymatgen.io.gaussian import GaussianInput
        from pymatgen.io.babel import BabelMolAdaptor

        fmt = "" if fmt is None else fmt.lower()
        fname = os.path.basename(filename or "")
        if fmt == "xyz" or fnmatch(fname.lower(), "*.xyz*"):
            writer = XYZ(self)
        elif any([fmt == r or fnmatch(fname.lower(), "*.{}*".format(r))
                  for r in ["gjf", "g03", "g09", "com", "inp"]]):
            writer = GaussianInput(self)
        elif fmt == "json" or fnmatch(fname, "*.json*") or fnmatch(fname,
                                                                   "*.mson*"):
            if filename:
                with zopen(filename, "wt", encoding='utf8') as f:
                    return json.dump(self.as_dict(), f)
            else:
                return json.dumps(self.as_dict())
        elif fmt == "yaml" or fnmatch(fname, "*.yaml*"):
            import ruamel.yaml as yaml

            if filename:
                with zopen(fname, "wt", encoding='utf8') as f:
                    return yaml.safe_dump(self.as_dict(), f)
            else:
                return yaml.safe_dump(self.as_dict())

        else:
            m = re.search(r"\.(pdb|mol|mdl|sdf|sd|ml2|sy2|mol2|cml|mrv)",
                          fname.lower())
            if (not fmt) and m:
                fmt = m.group(1)
            writer = BabelMolAdaptor(self)
            return writer.write_file(filename, file_format=fmt)

        if filename:
            writer.write_file(filename)
        else:
            return str(writer)