There are two reasons for writing a key signature. Firstly, it saves writing out lots of sharps or flats during the piece. Secondly, it helps the player to think in the key (music) of the piece. This helps to understand the music better.