我正在尝试创建一个创建csv文件并将其保存在临时目录中的简单应用程序。它似乎工作但我在哪里或如何访问该文件?
以下是我用来创建csv文件的示例代码:
// CSV file creating
func creatCSV() -> Void {
let fileName = "Example.csv"
let path = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)
let csvText = "Time,Date,Heartrate(BPM)\n"
do {
try csvText.write(to: path!, atomically: true, encoding: String.Encoding.utf8)
} catch {
print("Failed to create file")
print("\(error)")
}
print(path ?? "not found")
}
答案 0 :(得分:0)
要写入文件:
func createCSV() -> String? {
let fileName = "Example.csv"
let tempDir = NSTemporaryDirectory()
let fileURL = URL(fileURLWithPath: tempDir, isDirectory: true).appendingPathComponent(fileName)
let csvText = "Time,Date,Heartrate(BPM)\n"
do {
try csvText.write(to: fileURL, atomically: true, encoding: .utf8)
return fileURL.path
} catch {
print("Failed to create file: \(error)")
return nil
}
}
从文件中读取:
func readCSV(path:String) throws {
let text = try String(contentsOfFile: path)
print("I read the following from the file: \(text)")
}
使用两者的示例:
if let path = createCSV() {
print("Path was \(path)")
try readCSV(path: path)
}