【问题标题】:Append data to txt file in Swift 3 [duplicate]在 Swift 3 中将数据附加到 txt 文件 [重复]
【发布时间】:2018-02-28 15:28:09
【问题描述】:

基本上,我正在尝试使用 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)")
}

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

【问题讨论】:

  • 请使用if let fileHandle = try? FileHandle(forUpdating: fileURL) 代替if let fileHandle = FileHandle(forReadingAtPath: fileURL.absoluteString)

标签: ios csv text swift3 append


【解决方案1】:

您可以在检查文件是否已存在后使用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

【讨论】:

  • 写入后不要忘记关闭文件句柄。
  • 底部没有“发布您的答案”框来显示我所做的并且这里没有足够的字符...但这也不起作用。
  • 如果您有更多要添加的问题,您应该编辑您的原始问题。并请说明“这也不起作用”的意思。出了什么问题?
  • 哦,被标记为重复是否会阻止我进一步讨论和发布我所做的事情?
  • 不,您应该仍然可以编辑您的问题。在那里发布代码,因为 cmets 不适合发布长代码。
猜你喜欢
  • 2012-06-03
  • 1970-01-01
  • 2016-08-12
  • 2017-03-21
  • 2021-05-05
  • 2016-03-11
  • 2015-02-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多