ios - 将数据 append 到 Swift 3 中的 txt 文件

标签 ios csv text swift3 append

<分区>

基本上,我正在尝试使用 Swift 3 执行此操作:

write a titleString to file
For i=1 to n
    newString = createNewString()  //these may look like "1: a, b, c"
    append each new string to end of file
next i

这是我所做的:

let fileURL = URL(fileURLWithPath: completePath)
let titleString = "Line, Item 1, Item 2, Item 3"
var dataString: String
let list1 = [1, 2, 3, 4, 5]
let list2 = ["a", "b", "c", "d", "e"]
let list3 = ["p", "q", "r", "s", "t"]


for i in 0...4 {
    dataString =  String(list1[i]) + ": " + list2[i] + list3[i] + "\n"

    //Check if file exists
    if let fileHandle = FileHandle(forReadingAtPath: fileURL.absoluteString) {
        fileHandle.seekToEndOfFile()
        fileHandle.write(dataString.data(using: .utf8)!)
    } else { //create new file

        do {
            try titleString.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
        } catch let error as NSError {
            print("Error creating file \(error)")
        }

    }
    print(dataString)
    print("Saving data in: \(fileURL.path)")
}

我在文件中得到的只是 titleString。其他字符串不显示。

最佳答案

在检查文件是否已存在后,您可以使用 FileHandle 追加现有文件。

let titleString = "Line, Item 1, Item 2, Item 3"
var dataString: String
let list1 = [1, 2, 3, 4, 5]
let list2 = ["a", "b", "c", "d", "e"]
let list3 = ["p", "q", "r", "s", "t"]

do {
    try "\(titleString)\n".write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
} catch {
    print(error)
}

for i in 0...4 {
    dataString =  String(list1[i]) + ": " + list2[i] + list3[i] + "\n"
    //Check if file exists
    do {
        let fileHandle = try FileHandle(forWritingTo: fileURL)
            fileHandle.seekToEndOfFile()
            fileHandle.write(dataString.data(using: .utf8)!)
            fileHandle.closeFile()
    } catch {
        print("Error writing to file \(error)")
    }
    print(dataString)
    print("Saving data in: \(fileURL.path)")
}

输出:

Line, Item 1, Item 2, Item 3
1: ap
2: bq
3: cr
4: ds
5: et

关于ios - 将数据 append 到 Swift 3 中的 txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46307310/

相关文章:

xml - 将CSV文件转换为适当的XML格式

swift - 快速保存多行文本

ios - 可以添加到 Xcode 的 dae 文件的最大大小是多少

python - 如何将字符串作为参数传递给 Python csv writerow?

python - CSV 阅读器对象不读取整个文件 [Python]

text - 更改 Sublime Text 3 中的高亮颜色?

R - 'NA' 文本被视为 N/A

ios - 接听电话时 AMSlideMenu UI 困惑(通话中状态栏)

ios - ViewController 上的 .xib 文件初始化 UIView 用户交互不起作用

iphone - 在 Storyboard iphone 中 ScrollView