Create folder and file using Google Apps Script

In this post, I will show you Create folder and file using Google Apps Script in Google Drive.

Create folder and file using Google Apps Script in Google Drive

Create folder and file using Google Apps Script

The following function will create a folder named My Folder in your Google Drive and then inside that folder, it will create a file named My File.txt. It will also write some text (Lorem ipsum) in that file.

function createFileFolder() {  
  // Create folder
  var folder = DriveApp.createFolder('My Folder');
  // Create file inside folder
  var file = folder.createFile('My File.txt', 'Lorem ipsum', MimeType.PLAIN_TEXT); 
}

Simple – Create folder under the Parent folder ID

Here, we are going to add a folder under the Parent folder. It doesn’t matter if the folder already exists, we’ll just create another one.

//Creates a folder as a child of the Parent folder with the ID: FOLDER_ID
function createFolderBasic(folderID, folderName) {
  var folder = DriveApp.getFolderById(folderID);
  var newFolder = folder.createFolder(folderName);
  return newFolder.getId();
};
 
function start(){
  //Add your own folder ID here: 
  var FOLDER_ID = '130KbplcZX1AzJUD3vq2uAaRXmN-PaTuK';
  //Add the name of your folder here:
  var NEW_FOLDER_NAME = "The New Folder";
  var myFolderID = createFolderBasic(FOLDER_ID, NEW_FOLDER_NAME);
  Logger.log(myFolderID);
};

Medium – Create a folder only if that folder name does not exist in the Parent folder

In this, we only create a folder if the folder does not exist. We will return the folder id of either the new folder or the existing folder.

//Create folder if does not exists only
function createFolder(folderID, folderName){
  var parentFolder = DriveApp.getFolderById(folderID);
  var subFolders = parentFolder.getFolders();
  var doesntExists = true;
  var newFolder = '';
  // Check if folder already exists.
  while(subFolders.hasNext()){
    var folder = subFolders.next();
    //If the name exists return the id of the folder
    if(folder.getName() === folderName){
      doesntExists = false;
      newFolder = folder;
      return newFolder.getId();
    };
  };
  //If the name doesn't exists, then create a new folder
  if(doesntExists = true){
    //If the file doesn't exists
    newFolder = parentFolder.createFolder(folderName);
    return newFolder.getId();
  };
};
function start(){
  //Add your own folder ID here: 
  var FOLDER_ID = '130KbplcZX1AzJUD3vq2uAaRXmN-PaTuK';
  //Add the name of your folder here:
  var NEW_FOLDER_NAME = "The New Folder";
  var myFolderID = createFolder(FOLDER_ID, NEW_FOLDER_NAME);
  Logger.log(myFolderID);
};

Detail of this post
https://yagisanatode.com/2018/07/08/google-apps-script-how-to-create-folders-in-directories-with-driveapp/

Other Post
https://automatescript.com/create-a-sidebar-in-google-sheets-using-google-apps-script/
https://automatescript.com/automatically-save-gmail-attachments-to-google-drive/