如何自动编辑文件内容swift操场



我想从我的MacOS中以编程方式编辑本地.playground文件,但如果文件已经创建,通常的写入方法似乎不起作用。我该怎么做?

let dir = try? FileManager.default.url(
for: .desktopDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: false
)
if let fileURL = dir?.appendingPathComponent("fileThatAlreadyExists").appendingPathExtension("playground") {

let outString = "Write this text to the file"
do {
try outString.write(to: fileURL, atomically: true, encoding: .utf8)
} catch {
print("Failed writing to URL: (fileURL), Error: " + error.localizedDescription)
}
}

我得到的错误是:

Failed writing to URL: file:///Users/scottlydon/Desktop/fileThatAlreadyExists.playground, Error: The file “fileThatAlreadyExists.playground” couldn’t be saved in the folder “Desktop”`. 

我认为,因为它已经存在,如果我将名称中的一个字符更改为尚未使用的名称,那么它就可以正常工作。

问题是您试图用文本文件覆盖目录。游乐场它不是一个文本文件,它是一个目录。如果你想把你的绳子放在操场上";文件";则需要重写";Contents.swift";位于操场包(目录(内的文件:

let fileURL = FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first!.appendingPathComponent("fileThatAlreadyExists.playground")
let contentsURL = fileURL.appendingPathComponent("Contents.swift")
let string = """
import Cocoa
var str = "Yes it works"
"""
do {
try Data(string.utf8).write(to: contentsURL, options: .atomic)
} catch {
print("Error:", error)
}

最新更新