append to a csv file in swift

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.swift
let filename = "data.csv"
let data = "1,2,3\n" // data to append to file

if let fileURL = try? FileManager.default
                    .url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
                    .appendingPathComponent(filename) {
    // open the file in append mode
    if let fileHandle = try? FileHandle(forWritingTo: fileURL) {
        fileHandle.seekToEndOfFile()
        // write the data to the file
        fileHandle.write(data.data(using: .utf8)!)
        fileHandle.closeFile()
    } else {
        // if the file doesn't exist yet, create it and write the header row
        FileManager.default.createFile(atPath: fileURL.path, contents: data.data(using: .utf8), attributes: nil)
    }
}
748 chars
18 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