Gre*_*reg 6 csv text append ios swift3
基本上,我试图用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
Run Code Online (Sandbox Code Playgroud)
这是我做的:
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)")
}
Run Code Online (Sandbox Code Playgroud)
我在文件中得到的只是titleString.其他字符串不显示.
FileHandle在检查文件是否已存在之后,您可以使用a 附加现有文件.
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)")
}
Run Code Online (Sandbox Code Playgroud)
输出:
Line, Item 1, Item 2, Item 3
1: ap
2: bq
3: cr
4: ds
5: et
Run Code Online (Sandbox Code Playgroud)