try:
    os.makedirs(dest_dir)
except OSError:
    pass
path = os.path.join(dest_dir, file_name)
with open(path, 'wb') as stream:
    stream.write('foo\n')
Writing to a new directory in Python without changing directory