如何在 swift 5 的文档目录中写入新行 CSV 文件?

How do I write a new row a CSV file in documents directory in swift 5?

我有一个功能,我想创建一个 CSV 文件(如果它不存在)并向其添加数据。如果它确实存在,我想在每次调用时将此数据添加为新行。

这是我当前的代码,目前它每次都会覆盖整个文件:

func writeTrackedSymptomValues(symptom: String, comment: String, time: String, timestamp: String) {
    symptomData = SymptomData()
    for _ in 0..<5 {
        symptomData.symptom = symptom
        symptomData.severity = self.severity
        symptomData.comment = comment
        symptomData.timestamp = timestamp
        symptom_data.append(symptomData!)
    }

    creatCSV()
}

func creatCSV() -> Void {
        let fileName = "symptom_data.csv"

        let path = self.getDocumentsDirectory().appendingPathComponent(fileName)
        var csvText = "Symptom,Severity,Comment,Time\n"


            let newLine = "\(symptomData.symptom),\(symptomData.severity),\(symptomData.comment),\(symptomData.timestamp)\n"
            csvText.append(newLine)


        do {
            try csvText.write(to: path, atomically: true, encoding: String.Encoding.utf8)
        } catch {
            print("Failed to create file")
            print("\(error)")
        }
        print(path ?? "not found")
}

func getDocumentsDirectory() -> URL {
    // find all possible documents directories for this user
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)

    // just send back the first one, which ought to be the only one
    return paths[0]
}

如何每次都添加一个新行?swift

使用 Warren 的建议解决了:

    var logFile: URL? {
        guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return nil }
        let fileName = "symptom_data.csv"
        return documentsDirectory.appendingPathComponent(fileName)
    }

此函数检查文件是否存在,如果不存在,它就像我原来的问题一样,如果存在,则使用 FileManager 添加新行。

    func createCSV() {
        guard let logFile = logFile else {
            return
        }

        guard let data = ("\(symptomData.symptom),\(symptomData.severity),\(symptomData.comment),\(symptomData.timestamp)\n").data(using: String.Encoding.utf8) else { return }

        if FileManager.default.fileExists(atPath: logFile.path) {
            if let fileHandle = try? FileHandle(forWritingTo: logFile) {
                fileHandle.seekToEndOfFile()
                fileHandle.write(data)
                fileHandle.closeFile()
            }
        } else {
            var csvText = "Symptom,Severity,Comment,Time\n"


                 let newLine = "\(symptomData.symptom),\(symptomData.severity),\(symptomData.comment),\(symptomData.timestamp)\n"
                 csvText.append(newLine)


             do {
                try csvText.write(to: logFile, atomically: true, encoding: String.Encoding.utf8)

             } catch {
                 print("Failed to create file")
                 print("\(error)")
             }
             print(logFile ?? "not found")
        }
    }