9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Google Colabを用いてGoogle Drive内のフォルダを削除する

Posted at

#はじめに

Google colabでスクリプトを作る際には、Google Driveと連携させるのが便利です。
スクリプトにより生成されたファイルはGoogle Driveに保存されていきます。

連携において不便に感じるのは、ColabからDrive内のフォルダを削除しようとするとエラーが出ることです。
中身が空のフォルダは消せますが、中のファイルを1個1個消すのも面倒です。

image.png

image.png

#Google Drive内のフォルダを削除するスクリプト

###フォルダごと削除したいとき
shutil.rmtreeを使うと、指定したフォルダごと削除できます。
削除されたフォルダはGoogle Driveのごみ箱に入ります。

import shutil

directory = 'ここにパスをコピペ'

try:
    shutil.rmtree(directory)
except FileNotFoundError:
    pass

###フォルダを残して中身だけ削除したいとき
中身ごと一度消してしまって、フォルダを作り直すと楽です。

import shutil

directory = 'ここにパスをコピペ'

try:
    shutil.rmtree(directory)
except FileNotFoundError:
    pass

#同名のフォルダを作成する
os.mkdir(directory)

###下位のフォルダは残して、中のファイルのみ削除したいとき
glob.globを用いる方法もあります。

import os

directory = 'ここにパスをコピペ'
files = os.listdir(directory)
print(directory)
print(files)

for i in files:
    try:
        os.remove(directory+'/'+i)
    except IsADirectoryError:
        pass

#おわりに
Colabのスクリプトの後ろにコピペしておくと、ちょくちょく掃除ができるので便利です。
では、快適なColab Lifeを!!

9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?