Nano not opening files on SD card

I think something about this script means it can't open/create an SD card. A test script worked fine, the test script used the same logic to open/create the file. Any ideas? When I run it, it goes through the set up, than prints "failed to create file in setup" after the other setup messages.

// Sensors: Temperature/Humidity, Gyro/Accelerometer/Temperature
/* 575381
 * Rocket_Setup.ino
 * 10/25/2024
 * Purpose:
 * read sensors
 * convert to readable file format
 * export to txt in sd card
 */

#include <SPI.h>
#include <SD.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include <Adafruit_MPU6050.h>

File file;
char fileName[] = "data.txt";
const int BME_CHIP = 0x76, MPU_CHIP = 0x68, SD_CHIP = 4, DELAY_TIME = 1000; // TODO: Find hardware port for SD card
Adafruit_BME280 bme;
Adafruit_MPU6050 mpu;
sensors_event_t accel, gyro, temp;
char charRead;

void setup()
{
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.println("Starting setup now.");
  
  unsigned status = bme.begin(0x76);
  if(!status)
  {
    Serial.println("No BME found! Check wiring or port.");
    while(1);
  }

  status = mpu.begin(0x68);
  if(!status)
  {
    Serial.println("No MPU found! Check wiring or port.");
    while(1);
  }
  
  pinMode(10, OUTPUT);  // Required for SPI

  delay(100); // small pause before SD.begin()
  
  status = SD.begin(SD_CHIP);
  if(!status)
  {
    Serial.println("No SD Card found! Check wiring or port.");
    while(1);
  }

  // Try to create the file here
  File file = SD.open(fileName, FILE_WRITE);
  if (file) {
    Serial.println("File created successfully");
    file.println("Initial log");
    file.close();
  } else {
    Serial.println("Failed to create file in setup");
    while (1);
  }
  
  Serial.println("End setup, start loop.");
}

void readFromFile()
{
  byte i=0; //counter
  char inputString[100]; //string to hold read string
  
  //now read it back and show on Serial monitor 
  // Check to see if the file exists:
  if (!SD.exists(fileName))
  {
    char buffer[100];
    sprintf(buffer, "%s doesn't exist", fileName);
  }
  Serial.println("Reading from simple.txt:");
  file = SD.open(fileName);

  while (file.available()) 
  {   
   char inputChar = file.read(); // Gets one byte from serial buffer
    if (inputChar == '\n') //end of line (or 10)
    {
      inputString[i] = 0;  //terminate the string correctly
      Serial.println(inputString);
      i=0;
    }
    else
    {
      inputString[i] = inputChar; // Store it
      i++; // Increment where to write next
      if(i> sizeof(inputString))
        {
        Serial.println("Incoming string longer than array allows");
        Serial.println(sizeof(inputString));
        while(1);
        }
    }
  }
 }

void writeToFile(String &input)
{
  file = SD.open(fileName, FILE_WRITE);
  if (file) // it opened OK
    {
    Serial.println("Writing to file");
    file.println(input);
    file.close();
    Serial.println("Done");
    }
  else 
    Serial.println("Error opening file");
}

void deleteFile()
{
 //delete a file:
  if (SD.exists(fileName)) 
    {
    Serial.println("Removing text file");
    SD.remove(fileName);
    Serial.println("Done");
   } 
}

String get_data()
{
  String data = "BME Readings: \n ";
  data.concat("Temperature: ");
  data.concat(bme.readTemperature());
  data.concat(" °C\n");

  data.concat("Pressure: ");
  data.concat(bme.readPressure() / 100.0f);
  data.concat(" hPa\n");

  data.concat("Approximate Altitude: ");
  data.concat(bme.readAltitude(1013.25));
  data.concat(" m");

  data.concat("Relative Humidity: ");
  data.concat(bme.readHumidity());
  data.concat(" %\n\n");


  data.concat("MPU Readings: \n");
  data.concat("dX = ");
  data.concat(gyro.gyro.x);
  data.concat(" °/s\n");
  data.concat("dY = ");
  data.concat(gyro.gyro.y);
  data.concat(" °/s\n");
  data.concat("dZ = ");
  data.concat(gyro.gyro.z);
  data.concat(" °/s\n");
  
  data.concat("aX = ");
  data.concat(accel.acceleration.x);
  data.concat(" °/s^2\n");
  data.concat("aY = ");
  data.concat(accel.acceleration.y);
  data.concat(" °/s^2\n");
  data.concat("aZ = ");
  data.concat(accel.acceleration.z);
  data.concat(" °/s^2\n");

  data.concat("Approx Temp: ");
  data.concat(temp.temperature);
  data.concat(" °C\n\n\n");
  return data; 
} 

void loop()
{
  // put your main code here, to run repeatedly:
  String data = get_data();
  writeToFile(data);

  delay(DELAY_TIME);
}

Try

char fileName[] = "/data.txt";

No change.

Post the test that worked.

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

const int chipSelect = 4;

void setup() {
  Serial.begin(9600);
  pinMode(10, OUTPUT);  // Important for SPI

  Serial.println("Initializing SD card...");
  if (!SD.begin(chipSelect)) {
    Serial.println("SD initialization failed!");
    return;
  }
  Serial.println("SD card initialized.");

  File dataFile = SD.open("test.txt", FILE_WRITE);
  if (dataFile) {
    dataFile.println("Hello from Nano!");
    dataFile.close();
    Serial.println("File written.");
  } else {
    Serial.println("Error opening file.");
  }
}

void loop() {}

Change the failing sketch to the same code as the working sketch at the line Sd. begin

Runs out of memory.
Look what it reports in a simulation

Starting setup now.
No BME found! Check wiring or port.
No MPU found! Check wiring or port.
Free Ram Size: 231
Failed to create file in setup

I removed the while() loops to better see what was happening and added the MemoryUsage library.

Try removing the type FILE to give:
file = SD.open(fileName, FILE_WRITE);
You already have a global variable file of the same type here:

EDIT

Indeed. RAM could also be a problem as already mentioned by @MaximoEsfuerzo :

Use the F() macro to keep such strings out of RAM:
Serial.println(F("No SD Card found! Check wiring or port."));

This does not make sense. If the file does not exist, print a message and read it anyway.

. . . and a similar question on Reddit: Can't open file on SD card? : arduino but without the same degree of useful responses that the OP has had in this forum.

I did what you recommended, and got it to work in the void setup{}

Yet it still doesn't work in write_to_file, I made sure the code was the same even

You have almost certainly got a low memory (RAM) problem as already mentioned.
Use the F() macro on all the Serial.print and Serial.println statements. Also here is a problem:

Simply say writeToFile( get_data( ) ) ; to avoid making another copy of that large String.