【问题标题】:Adding a new data on a new row in CSV file在 CSV 文件的新行上添加新数据
【发布时间】:2017-11-06 15:41:28
【问题描述】:

顺便说一句,我想使用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-loop 并且根本不保存

任何建议都会有所帮助

【问题讨论】:

    标签: ios arrays swift csv for-loop


    【解决方案1】:

    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 对所有其他数组进行索引。因此,您可能应该使用

    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。)

    【讨论】:

    • 但是数组0属于循环外的行,因为它是for循环行上方的静态数据
    • 现在可以了,看来问题不在代码上,而是在读取错误文件的 tableview 上
    • 查看我的答案的编辑。 (我不熟悉 CSV 库,所以我猜测那部分。)
    • @DuncanC 当 CSV 文件不存在时,我如何创建新的 CSV 文件,如果 CSV 文件存在,将数组数据添加到现有的 CSV 文件中?你能帮忙怎么做吗?
    猜你喜欢
    • 2012-07-09
    • 2016-07-02
    • 1970-01-01
    • 2017-08-21
    • 1970-01-01
    • 2018-05-20
    • 2021-09-02
    • 2018-06-10
    • 1970-01-01
    相关资源
    最近更新 更多