如何在swift中更改文档文件夹中的文件名
我的文档文件夹中有一些文件。我正在保存诸如“data_20201223163209.pdf”、“data_20201223171831.pdf”、“data_20201222171831.pdf”、“data_20201221171831.pdf”等文件。现在我想用诸如“newdata”等其他字符串替换“data”。所以我的文件应该是“newdata_20201223163209.pdf”,“newdata_20201223171831.pdf”,“newdata_20201222171831.pdf”,“newdata_20201221171831.pdf” 我的代码:如何在swift中更改文档文件夹中的文件名,swift,nsfilemanager,Swift,Nsfilemanager,我的文档文件夹中有一些文件。我正在保存诸如“data_20201223163209.pdf”、“data_20201223171831.pdf”、“data_20201222171831.pdf”、“data_20201221171831.pdf”等文件。现在我想用诸如“newdata”等其他字符串替换“data”。所以我的文件应该是“newdata_20201223163209.pdf”,“newdata_20201223171831.pdf”,“newdata_20201222171831.
do{
让path=NSSearchPathForDirectoriesInDomains(.documentDirectory、.userDomainMask,true)[0]
让documentDirectory=URL(fileURLWithPath:path)
让originPath=documentDirectory.appendingPathComponent(“数据”)
让destinationPath=documentDirectory.appendingPathComponent(“newdata”)
尝试FileManager.default.moveItem(位于:originPath,to:destinationPath)
}抓住{
打印(错误)
}
请帮助我解决此问题您只需获取目录的内容,过滤名称以“data_”开头的URL,迭代这些URL并重命名每个URL,然后使用新名称将其移动到同一目录。请注意,这假定目标位置没有具有新名称的文件
// Get the documents url
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
do {
// Get its contents
let contents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil)
print(contents)
// filter the contents that starts with "data_"
let dataFiles = contents.filter { $0.lastPathComponent.hasPrefix("data_") }
// iterate the source files
for srcURL in dataFiles {
// create the destinations appending "newdata_" + the source lastPathComponent dropping its "data_" prefix
let dstURL = documentsUrl.appendingPathComponent("newdata_" + srcURL.lastPathComponent.dropFirst(5))
// move/rename your files
try FileManager.default.moveItem(at: srcURL, to: dstURL)
}
} catch {
print(error)
}
“解决这个问题”问题是什么?未经用户同意,您不允许访问那里的文件。您是如何访问它们的?NSDocument的标签是什么?您好@Leo谢谢您的回答。当我们检查lastPathComponent时,“pdf”是此处compnet的最后一个路径。所以它的前缀是:-“data_20201223163209.”、“data_20201223171831.”、“data_20201222171831.”等等。所以它没有进入for循环。Pdf是路径扩展,你在使用macOS还是iOS?如果你正在使用macOS,你需要禁用沙箱功能@Leo Dabus大量存储。我的代码正在运行