To append to a CSV file in Swift, first open the file in append mode, then write the data to the file. Here's an example:
main.swift748 chars18 lines
In this example, we first get the URL to the document directory and create a file URL using the desired filename. If the file exists, we open it in append mode using FileHandle(forWritingTo:)
. Then we seek to the end of the file using seekToEndOfFile()
to ensure that we are appending to the end of the file. We then write the data to the file using write(_:)
and close the file handle.
If the file doesn't exist yet, we create it using createFile(atPath:contents:attributes:)
and pass in the data we want to write as the file's contents. In this example, we're assuming that the first row of the CSV file is the header row, so we're passing that in when we create the file. If your CSV file doesn't have a header row, you can pass in an empty string instead.
gistlibby LogSnag