moved f.close to be within the try, as it caused unbound local error