Append data to a text file without closing/reopening the text file every FixedUpdate()

I am trying to record the coordinates of the position of an object into a text file and my code is working fine and doing what I want. However, the way it is set up will keep opening and closing the file every time it writes a new line which seems unnecessary and hard drive intensive. My code looks like this:

When the key “1” is pressed, collectdata = true for 410 seconds. Writing to the text file begins and then after that amount of time it stops.

void Start ()
        {
            filePath = Path.Combine(Application.dataPath, folderName);
            filePath = Path.Combine(filePath, fileName);
            textFile = new FileInfo (filePath);
        }
      

    void FixedUpdate()
        {
            GameObject ROOMDATA = GameObject.FindGameObjectWithTag ("ROOMDATA");
            if (collectData == true)
            {
                writer = textFile.AppendText ();
                float x = ROOMDATA.transform.position.x;
                float z = ROOMDATA.transform.position.z;
                writer.WriteLine (x + "\t" + z);
                Debug.Log ("write to file");
            writer.close
        }
          
         }

    void Update ()
        {
        // Pressing 1 saves roomdata1
        if (Input.GetKeyDown ("1")) {
            collectData = true;
            StartCoroutine (WaitAndStop ());
            }

        }
    IEnumerator WaitAndStop()
    {
        yield return new WaitForSeconds(410);
        collectData = false;

    }
}

Why do you need to write it every frame ? If there no special reasons, you should store data to a variable, and write the file when WaitAndStop end.

That’s exactly what I need to do :slight_smile: