productiveGuser.com

Create a text file in Google Drive

Posted By: Harish
create a text file in google drive folder

We can only create a few types of files using Google Drive's GUI, in which creating a new text file is not present.

Basically, if we need a text file with content in our drive, we need to upload it.

But with Google Apps scripts, we can directly create a text file in the drive folder. We can use Google drive's createFile(name, content) function to create a text file.

We can also use createFile(name, content, MimeType) function to create a plain text file by passing MimeType.PLAIN_TEXT. In this post, we will be using this function to create a text file.

First, create a new project in the Google Apps Script dashboard and open the editor.

Replace the default function (which already exists) with the below function and run it to get the newly created text file's url. Visit creating and executing a Google Apps Script post for more info.

function createTextFile() {
  try {
    const folderName = "text folder"; //<-- change folder name of your choice
    DriveApp.createFolder(folderName);
    const textFolder = DriveApp.getFoldersByName(folderName);
    const folder = textFolder.next();
    const createdFile = folder.createFile(
      "New text file",
      "This is a text content (inside doublequotes) with which the text file will be created", //<-- add text content here
      MimeType.PLAIN_TEXT
    );
    const url = createdFile.getUrl()
    Logger.log(url)
  } catch (err) {
    Logger.log(err)
  }
}

At first, we are creating a google drive folder to store the text file. You can get more info by visiting creating a new google drive folder post about creating a google drive folder.

If you already have a folder, change the folderName variable's value to that folder name.

Now we will be using the createFile(name, content, MimeType) function to create a new text file.

Here, name is the text file name, content is the content of the text file and the MimeType is the type of file we are creating.

As we are creating a text file, its mime type will be MimeType.PLAIN_TEXT. You can also create other file types by replacing the mimetype of the file in the above code. Check more MimeTypes HERE.

After executing the function in the editor, you will get a text file url in the log. Use that to directly preview the file.

create a text file in google drive folder

Please note that, if you open a text file in google docs, a new doc file will be created and changes are only visible in this new doc file and not in the original text file.

Share is Caring

Related Posts