Oxygen is written as O2 when there are two oxygen atoms in the molecule. Pure oxygen doesn't generally exist as individual atoms, two oxygen atoms bond together to form an oxygen molecule. This is because oxygen is highly reactive, disconnected atoms have a very strong tendency to form bonds. If there's nothing else available, they'll bond to each other.
By convention, chemical equations are written to show the whole molecules involved. Since there are two oxygen atoms in each oxygen molecule, it's written with a 2.