writing to an SD card.

I am not the greatest programmer so I apologize in advance. But I have written some simple code to write sensor data from an arduino uno and an accelerometer to an SD card. It works, (sort of) but in my loop of writing 39 lines of data (time, sensor, index number) to the SD card it writes 13 lines of data and then goes back to zero and writes another 39 lines of data to my SD card giving a total of 53 lines of data on my SD card when (I thought) I only asked for 39 lines. Help? My code is very simple. Here is my code:

#include <SD.h>
File myFile;
// below are the variables for the accelerometer
int sleepPin= 5;
int xpin= A0;
int q;
void setup()
{
Serial.begin(9600);
pinMode(sleepPin,OUTPUT);
digitalWrite(sleepPin, HIGH);//turns off sleep mode and activates device
pinMode(xpin, INPUT);//input mode
digitalWrite(xpin, HIGH);//turn on pull up resistor
pinMode(10, OUTPUT);

if (!SD.begin(4)) {
Serial.println("initialization failed!");
return;
}
Serial.println("initialization done.");

myFile = SD.open("test.txt", FILE_WRITE);

if (myFile) {
for (q=0; q<39; q++){
myFile.println();
myFile.print(analogRead(xpin),DEC);
myFile.print("\t");
myFile.print(millis());
myFile.print("\t");
myFile.print(q);
}
// close the file:
myFile.close();

} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
} }

void loop()
{
}

Are you deleting the file before running the code?

Yes. I delete the file on the SD card every time.

Add a 5 second delay at the start of setup.

It's auto reset. The code uploads, runs 13 times while you open the serial monitor, then starts over.

Instead of the delay, you could do something like:

setup() {
  Serial.begin(9600);
  while(Serial.available() <= 0);
}

That'll cause setup() to wait for you to send something from the serial monitor.

Thank you, thank you, thank you. So helpful. Now that I know what is going on, I can cope. Thanks again.
-Ann