title: How can I write to a file, line by line in Swift 4
body: <p>I need help figuring out how to write repeatedly to the same, open, output file.
  I am using Swift 4.2. My searches and tests have turned up only code that writes a single text string to a file and then closes the file. The next opening overwrites the last one.  An example is shown below.  </p>
  
  <p>The problem is that I need to be able to write large numbers of records (say, 1.5 million) and perform calculations on each record just before it is written to a file.  That’s not feasible when the code will only write once before closing. I'm calling this "writing line by line", much like the opposite, to "read line by line." </p>
  
  <p>I tried to find an option in various Swift write statements and SO posts, but everything seems to be geared toward writing once then closing the file.  I tried an open for append, but that did not work and anyway it seems inefficient to open, close, reopen-append each time I want to write to a file. I tried some C code in Swift, using open(… and freopen(… but could not get something that the compiler wouldn't complain about. Hopefully, there is a way to do this all in Swift. The following code works nicely for one write.</p>
  
  <pre><code>let file0 = “test_file.txt”
  let s0 = ("This is a test line of text")
  do {
    try s0.write(to: NSURL(fileURLWithPath: file0) as URL, atomically: false, encoding: String.Encoding.utf8)
  } catch {
    print("Problem writing to file0")
  }
  </code></pre>
  
  <p>How can I adapt this code snippet to write a string, and then another and another etc, and before closing the file when it’s all done?  If not with this, is there Swift code that will do the job?</p>