def atomic_open(filename, mode='w'):
    '''
    Works like a regular `open()` but writes updates into a temporary
    file instead of the given file and moves it over when the file is
    closed.  The file returned behaves as if it was a regular Python
    '''
    if mode in ('r', 'rb', 'r+', 'rb+', 'a', 'ab'):
        raise TypeError('Read or append modes don\'t work with atomic_open')
    kwargs = {
        'prefix': '.___atomic_write',
        'dir': os.path.dirname(filename),
        'delete': False,
    }
    if six.PY3 and 'b' not in mode:
        kwargs['newline'] = ''
    ntf = tempfile.NamedTemporaryFile(mode, **kwargs)
    return _AtomicWFile(ntf, ntf.name, filename)