Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append data to txt file in Swift 3 [duplicate]

Basically, I am trying to do this with 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

Here is what I have done:

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)")
}

All I get in the file is the titleString. The other strings don't show up.

like image 801
Greg Avatar asked Sep 19 '17 18:09

Greg


1 Answers

You can use a FileHandle for appending the existing file after checking if the file already exists.

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)")
}

Output:

Line, Item 1, Item 2, Item 3
1: ap
2: bq
3: cr
4: ds
5: et
like image 69
Dávid Pásztor Avatar answered Oct 13 '22 18:10

Dávid Pásztor