Nano resetting once when writing to SD card

Hi all, I'm getting some weird behavior from my Nano that I'm using to write a text file to an SD card. In short, what I'm trying to do is check the SD card for files called "test1.txt", "test2.txt", "test3.txt", etc etc. and then creating (for example) a "test4.txt" file when "test4.txt" does not exist. Here's my code:

#include <SPI.h>
#include <SD.h>

const int chipSelect = 4;

void setup() {

  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  
  SD.begin(chipSelect);

  String fileName = "test1.txt";
  int i = 1;
  File dataFile = SD.open(fileName);
  
  while(i > 0){
    dataFile = SD.open(fileName);
    if(dataFile) {
      Serial.println(fileName + " exists");
      i += 1;
      dataFile.close();
      fileName = "test" + String(i) + ".txt";
    }else{
      i = 0;
      Serial.println(fileName + " does not exist");
      Serial.println("Creating "+ fileName);
      dataFile = SD.open(fileName, FILE_WRITE);
      Serial.println("Success!");
    }
  }
}

Note: void loop() {} is empty

If "test1.txt", "test2.txt", "test3.txt" already exist on the SD card, the output on the serial monitor looks like this:

test1.txt exists
test2.txt exists
test3.txt exists
test4.txt does not exist
Creating test4.txt
test1.txt exists
test2.txt exists
test3.txt exists
test4.txt exists
test5.txt does not exist
Creating test5.txt
Success!

Any idea what's going on here?

I wired the Nano according to this tutorial:https://www.circuito.io/app?components=9442,11022,1671987

Except I connect CS to D4

Unreadable wire diagrams are unreadable.
Unreadable wire diagrams in an unclickable link that needs another number of clicks to even see shows you don't care about the time of the people you're asking FREE help from.
A proper schematic of how it's wired tells a lot.
Your symptoms imply either a wiring error or a too weak power supply.

If it's a power / wiring thing causing a reset, it's funny that it resets exactly once each time. OP can you confirm it's always once and once only?

I'll try it on an Uno in a while, when I get a gap (and can find my SD card module....)

No reset for me on an Uno, with the SD module powered from the Uno's 5V.

I added this line to setup():

Serial.println("Starting setup()");

... and get this output:

Starting setup()
test1.txt exists
test2.txt exists
test3.txt exists
test4.txt does not exist
Creating test4.txt
Success!

edit: just for the hell of it, I ran it in PuTTY as well as the Serial Monitor: all good

Hal_Posoyan:
No reset for me on an Uno, with the SD module powered from the Uno's 5V.

How are the Nano and Uno themselves powered exactly?

wvmarle:
How are the Nano and Uno themselves powered exactly?

I can only speak for the Uno, which is on the USB of the laptop to which it is Serial.print()-ing.