You could use a context manager here. This way the file gets closed even if a exception occurs.

```py
with open(filename, 'w') as fd:
    dostuff()
```