簡體   English   中英

在CSV文件的新行上添加新數據

[英]Adding a new data on a new row in CSV file

我想使用https://github.com/yaslab/CSV.swift/issues將數組中的數據添加到CSV文件中,他們建議的方式是每行都需要聲明

try! csv.write(row: ["", ""])

例如,手動。

import Foundation
import CSV

let stream = OutputStream(toFileAtPath: "/path/to/file.csv", append: false)!
let csv = try! CSVWriter(stream: stream)

try! csv.write(row: ["id", "name"])
try! csv.write(row: ["1", "foo"])
try! csv.write(row: ["1", "bar"])

csv.stream.close()

無論如何,我需要使其自動創建新行,具體取決於數組內的對象數。 所以我通過將每個csv追加到數組中來更改了它

    func saveCSVFiles() -> URL {
    let itemList = objectNo
    let fileManager = FileManager.default

        let documentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
        csvFile = documentDirectory.appendingPathComponent("\(fileName!).csv")
        let path = csvFile

        let stream = OutputStream(url: csvFile!, append: false)
        let csv = try! [CSVWriter(stream: stream!)]
        try! csv[0].write(row: ["name", "x", "y", "width", "height"])

        for no in stride(from: 1, to: itemList.count, by: 1) {
            try! csv[no].write(row: [String(describing: objects.dataName[no]), String(describing: objects.dataX[no]), String(describing: objects.dataY[no]), String(describing: objects.boundingX[no]), String(describing: objects.boundingY[no])])
    }
        csv[itemList.count].stream.close()

        print("yesss!", "\(fileName!)")
    return path!
}

但是每次我嘗試保存它時,都會導致致命錯誤:索引超出了循環for行的范圍 ,並且根本不保存

任何建議都會有幫助

Swift(和大多數語言)中的數組從零開始。 因此,您希望for循環從0到count-1。 有一個內置構造..< ,非常適合:

for no in 0..< itemList.count {
            try! csv[no].write(row: [String(describing: objects.dataName[no]), String(describing: objects.dataX[no]), String(describing: objects.dataY[no]), String(describing: objects.boundingX[no]), String(describing: objects.boundingY[no])])
}

編輯

聽起來您需要索引從1到itemList.count csv數組,以及從0到itemList.count - 1所有其他數組的itemList.count - 1 因此,您可能應該使用

for no in 0..< itemList.count {
            try! csv[no+1].write(row: [String(describing: objects.dataName[no]), String(describing: objects.dataX[no]), String(describing: objects.dataY[no]), String(describing: objects.boundingX[no]), String(describing: objects.boundingY[no])])
}

(請注意csv的索引中的+1 )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM