LoginSignup
8
2

More than 3 years have passed since last update.

デスクトップを綺麗にしたい~Pythonで不要ファイル自動削除~

Posted at

デスクトップが汚くなってきた...

ファイルとショートカットだらけになってきた。
dirty_desktop.jpg

ファイルを片付けるのもめんどくさい。
対策として以下のことを試すことにした。

  1. 一時的に使用するファイルを\tmpフォルダにまとめる
  2. 大切なファイルはオンラインストレージにバックアップする(手動)
  3. \tmpフォルダにあるファイルのうち、一週間以上使っていないファイルは自動で削除

3.をPythonで書いた。

完成!「ファイル自動削除くん.bat」

使い方

  1. 不要ファイルを削除したいフォルダにファイル自動削除くん.batを入れる(お好きな場所にどうぞ)
    where_to_place.png

  2. .batをダブルクリックして実行

  3. 一週間以上アクセスしていないファイルがすべて削除される
    executed-1597238348957.jpg

コード

Gistにも上げた(シンタックスハイライトのために.pyにしてる)→ dannyso16/delete_unused_files.py

ただしプログラムは以下の環境で作った。

  • Windows 10 Education
  • Python 3.7

PythonプログラムはMacやLinuxでも動作する(はず)です。コードはやや新しいPythonの書き方をしている部分があるので3.6以降だと安心です。
以下完成したコード(.batファイルにPythonプログラムを書いている)

REM = r"""
SET PYTHON_EXE="python.exe"
%PYTHON_EXE% %0 %1
PAUSE
EXIT
"""

import os
import glob
import time
import send2trash

root_dir = os.path.abspath(os.path.dirname(__file__))
os.chdir(root_dir)

files = glob.glob("./**")
print(f"{len(files)} files here.")
print(files)
current_time = time.time()

print("Now deleting unused files...")
for f in files:
    name, ext = os.path.splitext(f)
    if ext == ".bat":
        continue
    atime = os.path.getatime(f)  # last access time
    ctime = os.path.getctime(f)  # last metadata change time
    mtime = os.path.getmtime(f)  # last modification time

    # delete file which you don't access within a week
    days_from_last_access = (current_time - atime)/3600/24
    if (days_from_last_access >= 7):
        send2trash.send2trash(f)
        print(f"--- {f}")

print("Completed.")


コードの工夫ポイント

多くは第38回ゼロからはじめるPython「Pythonで不要ファイルを一括削除しよう」を参考にしている。

1. ゴミ箱に移す

os.removeではファイルが完全に消え去ってしまうので念のためゴミ箱に移す。PythonではSend2trashが便利でWindowsだけでなくMacやLinuxでも、よしなにやってくれる。

# pip install Send2Trash しましょう
import send2trash

# ゴミ箱に入れる
send2trash.send2trash('/path/of/file')


2. batファイルをどこでも実行できるようにする

最初は「どうせデスクトップで使うし…」と思ってパスをべた書きしてた。

root_dir = "./path/for/desktop/tmp"
以下略

しかし不要なファイルがたまるのはデスクトップだけでない。ゴミ箱と化している「ダウンロード フォルダ」やスクショをためる「ピクチャ フォルダ」も掃除したかったので、.batのファイルがある場所にカレントディレクトリを設定するようにした。

root_dir = os.path.abspath(os.path.dirname(__file__))
os.chdir(root_dir)


3. 消す条件はお好きにどうぞ

ファイルを削除する部分を抜粋する。

for f in files:
    name, ext = os.path.splitext(f)
    if ext == ".bat":
        continue
    atime = os.path.getatime(f)  # last access time
    ctime = os.path.getctime(f)  # last metadata change time
    mtime = os.path.getmtime(f)  # last modification time

    # delete file which you don't access within a week
    days_from_last_access = (current_time - atime)/3600/24
    if (days_from_last_access >= 7):
        send2trash.send2trash(f)
        print(f"--- {f}")

ここでは

  • 拡張子.batは削除しない
  • 7日間アクセスしていないファイルを削除する

ようにした。お好みで「〇日間編集していないファイルを削除する」などに変えて使ってください。


最後に

小さい自動化でも結構たのしいし、定期実行するように設定しておけば便利そう。「もっと簡単にデスクトップをきれいにするやり方があるよ」とか「コードはこう書くといいよ」はGist上かQiitaで気軽に教えてください。

あとどうでもいいけど、デスクトップはとってもきれいになりました。
desktop.jpg
Just Do It !! 極度掃除(しなさい)

これは以下のツイートに影響されています。


参考

第38回ゼロからはじめるPython「Pythonで不要ファイルを一括削除しよう」

dannyso16/delete_unused_files.py

8
2
3

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
8
2