<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def _write_newname_file(in_file, out_file, mappings):
 """Re-write an input file with contigs matching the correct reference. """

    with utils.open_gzipsafe(in_file) as in_handle:
        with open(out_file, "w") as out_handle:
            for line in in_handle:
                if line.startswith("#"):
                    out_handle.write(line)
                else:
                    parts = line.split("\t")
                    new_contig = mappings.get(parts[0])
                    if new_contig:
                        parts[0] = new_contig
                        out_handle.write("\t".join(parts))