我要像"Hi;Test;Pen"
一些文本添加到我的.csv文件。如何将文本添加到Swift中的.csv数据中?
我已经使用了CSVImporter将.csv的文本插入到我的Xcode项目。下面是代码,我已经使用它:
guard let VokabelPath = Bundle.main.path(forResource: ResourceExample, ofType:"csv") else {
debugPrint(ResourceExample + " not found")
return
}
let importer = CSVImporter<[String]>(path: VokabelPath, delimiter: ";")
let importedRecords = importer.importRecords { $0 }
for record in importedRecords {
self.Vokabeln.insert(record, at: self.Vokabelzähler)
self.Vokabelzähler += 1
}
但对于一些原因,我想
- 在文件中添加一些文件
- 改变的东西(例如,在4号线)
- 删除该文件中的文本(例如
filetext = ""
我曾尝试使用this政党成员里尔和我已经提出这样的代码:
let fileName = "Tasks.csv"
let path = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)
var csvText = "Test;Example;Apple;Pen\n"
do {
try csvText.write(to: path!, atomically: true, encoding: String.Encoding.utf8)
} catch {
print("Failed to create file")
print("\(error)")
}
guard let VokabelPath = Bundle.main.path(forResource: "Tasks", ofType:"csv") else {
debugPrint("Tasks not found")
return
}
let importer = CSVImporter<[String]>(path: VokabelPath, delimiter: ";")
let importedRecords = importer.importRecords { $0 }
for record in importedRecords {
self.Vokabeln.insert(record, at: self.Vokabelzähler)
self.Vokabelzähler += 1
print(record)
}
但他只打印“任务未找到”。我的错误是什么?
我希望你能帮助我,
谢谢。
编辑:
谁做的第一个答案的人写的,我无法保存在包文件。 他写信给我,我应该用NSSearchPathForDirectoriesInDomains
所以我已经更新了我的代码和这个作品:
let DownloadPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
let VokabelPath = DownloadPath.appendingPathComponent("Tasks.csv")
let InhaltData = Inhalt.data(using: .utf8)
print(VokabelPath)
FileManager.default.createFile(atPath: VokabelPath, contents: InhaltData, attributes: nil)
let importer = CSVImporter<[String]>(path: VokabelPath, delimiter: ";")
let importedRecords = importer.importRecords { $0 }
for record in importedRecords {
self.Vokabeln.insert(record, at: self.Vokabelzähler)
self.Vokabelzähler += 1
}
但我有一个进一步的问题: 我甲肝一些DATAS在我的Xcode项目,我可以用Bundle.main
让他们。但是我只想使用一个函数,所以有可能使用NSSearchPathForDirectoriesInDomains
?
我已经尝试过,但如果我想写一个新的文件的部分'警卫让VokabelPath = Bundle.main.path(forResource:ResourceExample,ofType:“csv”)其他{ debugPrint(ResourceExample +“not found”) return }'我只出现错误。 –
您无法将新文件写入Bundle路径:)该软件包基本上是您的应用程序文件 - 您无法修改该文件。相反,您必须将新文件保存到设备上沙盒文档文件夹中的路径。您可以通过'NSSearchPathForDirectoriesInDomains'方法获取文档文件夹,然后将您要创建的新CSV文件的文件名添加到文件夹中... – Fahim
我不知道如何做到这一点。我编辑了我的问题,我希望你现在可以说我,我做错了什么,以及它应该如何工作的例子:)。谢谢。 –