How does one save oneself from bad habits?

There is no mysterious method for this purpose. Activate your mind against that evil. The mind is the source of all kinds of desires. So, you have to train your mind, and then the mind itself will control all those evils. At present your evil switch is on, develop the will power and then the mind will put it off. And then certainly you will be saved from committing all those evils.