You should move all this logic into a separate function, `clean_metadata` or similar. If successful, it returns the file-like object of the cleaned file; otherwise it can return None or raise an exception (that must be caught).