如果文件不存在,如何在文档文件夹中创建文件?

How to create a file in the documents folder if one doesn't exist?

我有以下写入文件末尾的代码。但是,我该如何修改行为,以便在 "output.txt" 不存在时创建它?

提前致谢!

func writeFile(){

    let str = "\n" + nominationKeyForWhenCellSelected! + "," + "1"
    let datafromString = str.data(using: String.Encoding.utf8)
    let filename = getDocumentsDirectory().appendingPathComponent("output.txt")


    do {
        let fileHandle = try FileHandle(forWritingTo: filename)
        fileHandle.seekToEndOfFile()
        fileHandle.write(datafromString!)

    } catch {

    }
}

使用文件管理器检查文件是否存在。如果没有,只需写入数据,否则按照您的操作追加。但是不要忘记关闭文件句柄。

do {
    if FileManager.default.fileExists(atPath: filename.path) {
        let fileHandle = try FileHandle(forWritingTo: filename)
        fileHandle.seekToEndOfFile()
        fileHandle.write(datafromString!)
        fileHandle.closeFile()
    } else {
        datafromString.write(to: filename)
    }
} catch {
    print(error)
}