The most likely reason for your door opening and closing on its own is because the wall surrounding the door is likely leaning one way or the other. Gravity does the rest then and causes the door to move even when you aren’t touching it.
The key to fixing a door like this is to deal with hinges. Make sure the door is closed, and starting with the top hinge and using a hammer and a chisel, tap the top of the pin upwards (if you have a newer door, you may be able to tap the pin out from the bottom, if there is nothing blocking it).
Keep tapping upwards on the pin until it comes all the way out. Once you have the pin in hand, use a block of wood, or another surface that you don’t mind getting dinged up, and place the pin on the surface. Using your hammer, tap the pin fairly hard once, creating a slight bend.
Once you have a bend in your pin, you can place it back into the hinge by tapping it back down into the hinge slot with your hammer.
Once it’s back in, see if your door will stay put. If it does, congrats! You’re Done! If not, repeat the same steps with the second door hinge. Once you complete both, your door should be good as new.