Write content to given filename. Checks for zero-sized files.
    If encoding is given writes to a codec.open() file.

def writeFile(filename, content, encoding=None):
    """Write content to given filename. Checks for zero-sized files.
    If encoding is given writes to a codec.open() file."""
    if not content:
        raise OSError("empty content for file %s" % filename)

    def getfp(filename, encoding):
        """Get open file object."""
        if encoding:
            return codecs.open(filename, 'w', encoding)
        return open(filename, 'wb')

    try:
        with getfp(filename, encoding) as fp:
            fp.write(content)
            fp.flush()
            os.fsync(fp.fileno())
            size = os.path.getsize(filename)
            if size == 0:
                raise OSError("empty file %s" % filename)
    except Exception:
        if os.path.isfile(filename):
            os.remove(filename)
        raise
    else:
        out.info(u"Saved %s (%s)." % (filename, strsize(size)))