Enhance dedup logic to handle whitespace
Use defer right after the open/create to properly close the file