Copy folder to a non-empty directory

462 views Asked by At

Is it possible to copy a folder to a non empty destination without deleting the contents of the destination folder first? My current implementation is as follows

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

What i need to achieve is overwrite the contents of destination folder with that of source folder.

1

There are 1 answers

0
Manuel On

The call removeItemAtPath_error deletes the destination directory and copyItemAtPath_toPath_error creates a directory of the same name as the deleted one, hence it is empty.

As a side note, the naming of your NSFileManager instance is somewhat misleading, as it is not a folder object but a file manager instance reference.

An example of how this can be done (I'm unfamiliar with PyObjC, so this is only for inspiration):

# 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);

I am assuming that this recursively copies the directories from the source and maintains the directory tree.