create a new file if mode is append and the file does not exist

Currently if the write mode is append and the output file does not exists, the script will crash. This PR fixes the issue and unifies the append and write modes, and there is some duplicated code.