Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I copy & move a file to a folder in Google Apps Script?

Is there a way to copy and rename a file and move that copy to a particular folder without having a second copy in the root folder? I have used combinations of copy, rename, move in different order, but each time, I still end up with a copy of the renamed file the root drive. Is this by default? It is annoying to say the least.

like image 441
user1070396 Avatar asked Dec 04 '22 00:12

user1070396


2 Answers

In the new version of google apps script all you need to acheive your task is the following:

file.makeCopy("new name", folder);
like image 160
Riyafa Abdul Hameed Avatar answered Apr 21 '23 03:04

Riyafa Abdul Hameed


EDIT : I had a look at your original question (before edit) and from there I understood the confusion you made about how files and folders work in Google Drive.

When you make a copy of a file you get a new file in the root folder, when you add this new file to another folder you have to consider that as sticking a label on this file without creating any new copy of it.

You can actually see the file in both the root and the other folder but it is the very same file with 2 different labels! (and you did notice that since you tried to delete it and saw it was deleted in both places)

The only thing you have to do to get the new file in its folder and not shown in the root it to remove the "root label".

That's how Google drive works. And when you think about it and compare to a local hard disk storage it gets logical : when you move a file from one folder to another on the same logical drive you don't move data (ie the bytes on the disk) but simply tell the disk operating system that this file is somewhere else on the map.

So consider Google Drive as a (very) large disk unit with billions on files that you can't move but on which you can stick as many labels as you want ;-) (the most important label being your Google account ID !)

And to play with these labels in the case you describe just try this simple function :

function copyAndMove(file,folder){
var newfile=file.makeCopy('copy of '+file.getName());// here you can define the copy name the way you want...
newfile.addToFolder(folder);//  add the copy to the folder
newfile.removeFromFolder(DocsList.getRootFolder());// and remove it from your root folder
}

to test it just use the 2 required parameters : the file object anf the folder object that you can get from many different methods, see the DocsList documentation for details on how to get it if you need to but I guess you already know that ;-)

like image 34
Serge insas Avatar answered Apr 21 '23 03:04

Serge insas