Use proper file handling functions instead of str pasting