To avoid leaving with an empty file, consider using:
```
with open(fname, 'w') as f:
    with csv.writer(f) as w:
        ...
```