raphre:
Is there anyway to keep that from happening?
The reset is triggered by the serial port DTR line going low and pulling the Arduino reset pin down. You can prevent the Arduino from resetting when that happens by connecting a capacitor between reset and ground. It might be better to consider whether you actually need to open and close the port repeatedly - it's not good practice.