在Swift中将两个字符串数组写入CSV文件可以通过以下步骤实现:
let column1Data = ["Apple", "Banana", "Orange"]
let column2Data = ["Red", "Yellow", "Orange"]
let fileURL = URL(fileURLWithPath: "/path/to/file.csv")
do {
let fileHandle = try FileHandle(forWritingTo: fileURL)
defer {
fileHandle.closeFile()
}
for (index, value) in column1Data.enumerated() {
let line = "\(value),\(column2Data[index])\n"
if let data = line.data(using: .utf8) {
fileHandle.write(data)
}
}
} catch {
print("Error writing to file: \(error)")
}
完整的代码示例如下:
let column1Data = ["Apple", "Banana", "Orange"]
let column2Data = ["Red", "Yellow", "Orange"]
let fileURL = URL(fileURLWithPath: "/path/to/file.csv")
do {
let fileHandle = try FileHandle(forWritingTo: fileURL)
defer {
fileHandle.closeFile()
}
for (index, value) in column1Data.enumerated() {
let line = "\(value),\(column2Data[index])\n"
if let data = line.data(using: .utf8) {
fileHandle.write(data)
}
}
} catch {
print("Error writing to file: \(error)")
}
这段代码将两个字符串数组中的数据按照CSV格式写入了指定路径的文件。你可以根据实际需求修改数组数据和文件路径。
领取专属 10元无门槛券
手把手带您无忧上云