'Write a zone to a file.
@param f: file or string.  If I{f} is a string, it is treated
as the name of a file to open.
@param sorted: if True, the file will be written with the
names sorted in DNSSEC order from least to greatest.  Otherwise
the names will be written in whatever order they happen to have
in the zone\'s dictionary.
@param relativize: if True, domain names in the output will be
relativized to the zone\'s origin (if possible).
@type relativize: bool
@param nl: The end of line string.  If not specified, the
output will use the platform\'s native end-of-line marker (i.e.
LF on POSIX, CRLF on Windows, CR on Macintosh).
@type nl: string or None'

def to_file(self, f, sorted=True, relativize=True, nl=None):

    str_type = string_types
    if (nl is None):
        opts = 'wb'
    else:
        opts = 'wb'
    if isinstance(f, str_type):
        f = open(f, opts)
        want_close = True
    else:
        want_close = False
    try:
        if sorted:
            names = list(self.keys())
            names.sort()
        else:
            names = self.iterkeys()
        for n in names:
            l = self[n].to_text(n, origin=self.origin, relativize=relativize)
            if isinstance(l, text_type):
                l = l.encode()
            if (nl is None):
                f.write(l)
                f.write('\n')
            else:
                f.write(l)
                f.write(nl)
    finally:
        if want_close:
            f.close()
