The preferred way of doing this:

```python
with open(....) as fd:
    fd.write(...)
```

This pattern uses a **context manager**. You can read more about them [here](https://docs.python.org/dev/reference/datamodel.html#context-managers).