Code won't write to SD card file in void setup!!!

Please see my code below:

I am very new to Arduino and coding so would be grateful for any explanation to what i’m doing wrong as well as a description of how a modified code would work.

The code itself seems to run fine as in the RPM function works and writes to the SD card.

What I am trying to do is add the text line “New Run” into the file when ever the reset button is pressed (program restarts), so that I can differentiate between different tests/runs.

I thought the easy way would be to add the code into the void setup but it isn’t working in its present form. (I’ve tried other methods of code also but still no joy!!).

Thanks for taking the time to look at my post.

#define STABLE_TIME (60 * 1000000) / (maxRpm * 5)
#include <SPI.h>
#include <SD.h>

const unsigned long maxRpm = 10000;
const word printInterval = 1000; //ms
const byte sensorPin = 2;
const int chipSelect = 10;

volatile unsigned long previousTime, count;
unsigned long previousPrint, rpm;
unsigned long time;

void setup()
{
  File dataFile;
Serial.begin(115200);

  

  dataFile = SD.open("RPMlog.txt", FILE_WRITE);
  
  if (dataFile) {
    dataFile.println("new run");
    dataFile.close();
   }
  
    
    if (!SD.begin(chipSelect)) {
  Serial.println("Card not inserted");
    }

  Serial.println("Card Present");

 attachInterrupt(digitalPinToInterrupt(sensorPin),rpm_func, CHANGE); 
 
}

    
void loop() {

  String dataString = "";
  
  if ((millis() - previousPrint) >= printInterval ) {
    Serial.print("RPM = ");
    
    dataString += "RPM = ";
    dataString += String(rpm, DEC);
    
    time = millis();
    previousPrint = millis();
    noInterrupts();
    unsigned long previousTimeCopy = previousTime;
    interrupts();
    if (count > 0) rpm = (60 * 1000000) / ( micros() - previousTimeCopy);
    Serial.println(rpm, DEC);
    
  File dataFile = SD.open("RPMlog.txt", FILE_WRITE);

  // if the file is available, write to it:
  if (dataFile) {
    dataFile.println(dataString);
    dataFile.close();
   }
  // if the file isn't open, pop up an error:
  else {
    Serial.println("error opening RPMlog.txt");

    }
  }
}


  
void rpm_func()
{
  unsigned long currentTime = micros();
  if (currentTime - previousTime >= STABLE_TIME) count++;
  previousTime = currentTime;
}

Shouldn't SD.begin come before trying to open a file?

Many Thanks.

I knew it would be something really simple.

Kind Regards