将文件夹复制到非空目录

时间:2018-06-11 10:31:39

标签: file-handling nsfilemanager sketchapp cocoascript

是否可以将文件夹复制到非空目的地而不先删除目标文件夹的内容? 我目前的实施如下

var folderObject = NSFileManager.defaultManager();
folderObject.removeItemAtPath_error(toPath, nil);
folderObject.copyItemAtPath_toPath_error(fromPath, toPath, nil));

我需要实现的是用源文件夹覆盖目标文件夹的内容。

1 个答案:

答案 0 :(得分:0)

调用removeItemAtPath_error删除目标目录,copyItemAtPath_toPath_error创建一个与删除目录同名的目录,因此它是空的。

作为旁注,NSFileManager实例的命名有些误导,因为它不是文件夹对象而是文件管理器实例引用。

如何做到这一点的一个例子(我不熟悉PyObjC,所以这只是为了灵感):

# Define paths
var sourcePath = "/my/source/path/"
var targetPath = "/my/target/path/"

# Create reference to file manager
var fileManager = NSFileManager.defaultManager();

# Create array of all file and directory paths inside the source directory
var sourcePaths = fileManager.contentsOfDirectoryAtPath_sourcePath_error(sourcePath, nil); 

# For each source file or directory
for sourcePath in sourcePaths:

  # Copy the file or directory to the target path
  fileManager.copyItemAtPath_toPath_error(sourcePath, targetPath, nil);

我假设这会递归地复制源中的目录并维护目录树。

相关问题