Use Python to automatically clean up system garbage, no more 360 security guards

Python automatically cleans up system garbage, no more 360 ​​security guards

During the installation and use of Windows, quite a lot of junk files are generated, including temporary files (such as: .tmp, ._mp), log files ( .log), temporary help files ( .gid), disk check files ( .chk) , temporary backup files (eg: .old, *.bak), and other temporary files. Especially if the temporary folder "Temporary Internet Files" of IE is not cleaned up for a period of time, the cached files sometimes occupy hundreds of MB of disk space. These LJ files not only waste valuable disk space, but can also make the system run as slow as a snail in severe cases.

360 Security Guard is the most commonly used to clean up computer junk. After the cleanup is completed, N GB of space is released, not to mention how comfortable it is. But as a Pythoneer, it is natural to play something different. I would like to introduce a method to automatically clean up computer garbage by executing py scripts using task plan. Interested students can try it.

Students, don't be too serious, the method introduced in this article is definitely not comparable to 360. A long time ago, there was a .bat file on the Internet that can clean up computer junk files. The main purpose of this article is to change the posture to learn the os module of Python.

1. Clean up the target

File types in the system disk %system%:

【临时文件(*.tmp)】
【临时文件(*._mp)】
【日志文件(*.log)】
【临时帮助文件(*.gid)】
【磁盘检查文件(*.chk)】
【临时备份文件(*.old)】
【Excel备份文件(*.xlk)】
【临时备份文件(*.bak)】

User directory %userprofile% folder

【COOKIE】 cookies\*.*
【文件使用记录】 recent\*.*
【IE临时文件】 Temporary Internet Files\*.*
【临时文件文件夹】 Temp\*.*.

Folders under the Windows directory %windir%

【预读取数据文件夹】 prefetch\*.*
【临时文件】 temp\*.*

Python os

The Python os module provides a very rich method for processing files and directories. It will adapt to different operating system platforms and perform corresponding operations according to different platforms. When programming in python, it often deals with files and directories. At this time Inseparable from the os module.
I won’t introduce too much in detail. You can look at the official documents, and there is no need to study them carefully. Just know which one is used and how to check it.

https://docs.python.org/zh-cn/3/library/os.html

Python script

It’s better to build wheels than stand on the shoulders of giants, and find that bloggers have already written it, but it’s written in Python2, just change the place of print.

import os
del_extension = {
    '.tmp': '临时文件',
    '._mp': '临时文件_mp',
    '.log': '日志文件',
    '.gid': '临时帮助文件',
    '.chk': '磁盘检查文件',
    '.old': '临时备份文件',
    '.xlk': 'Excel备份文件',
    '.bak': '临时备份文件bak'
}
del_userprofile = ['cookies', 'recent', 'Temporary Internet Files', 'Temp']
del_windir = ['prefetch', 'temp']
SYS_DRIVE = os.environ['systemdrive'] + '\\'
USER_PROFILE = os.environ['userprofile']
WIN_DIR = os.environ['windir']

def del_dir_or_file(root):
    try:
        if os.path.isfile(root):
            os.remove(root)
            print ("file",root,"removed")
        elif os.path.isdir(root):
            os.rmdir(root)
            print("dir",root,"removed")

    except WindowsError:
        print("failure",root,"can't remove")

def formatSize(b):
    try:
        kb = b // 1024
    except:
        print("传入字节格式不对")
        return "Error"
    if kb > 1024:
        M = kb // 1024
        if M > 1024:
            G = M // 1024
            return "%dG" % G
        else:
            return "%dM" % M
    else:
        return "%dkb" % kb

class DiskClean(object):
    def __init__(self):
        self.del_info = {}
        self.del_file_paths = []
        self.total_size = 0
        for i,j in del_extension.items():
            self.del_info[i] = dict(name = j,count = 0 )

    def scanf(self):
        for roots,dirs,files in os.walk(USER_PROFILE):
            for files_item in files:
                file_extension = os.path.splitext(files_item)[1]
                if file_extension in self.del_info:
                    file_full_path = os.path.join(roots,files_item)
                    self.del_file_paths.append(file_full_path)
                    self.del_info[file_extension]['count'] += 1
                    self.total_size += os.path.getsize(file_full_path)

    def show(self):
        re = formatSize(self.total_size)
        for i in self.del_info:
            print(self.del_info[i]["name"],"共计",self.del_info[i]["count"],"个")
        return re

    def delete_files(self):
        for i in self.del_file_paths:
            print(i)
            del_dir_or_file(i)
if __name__ == "__main__":
    print("初始化清理垃圾程序")
    cleaner = DiskClean()
    print("开始扫描垃圾文件请耐心等待\n")
    cleaner.scanf()
    print("扫描成功,结果如下")
    re = cleaner.show()
    cleaner.delete_files()

After the call, save it as kill360.py and save it to the working directory of python. If you don’t know the working directory, you can run os.getcwd() to view it. In addition, you need to make sure that the installation directory of python has been added to the path system variable. Method: in the computer, right-click to open My Computer (this computer)\Properties\Advanced system settings\Environment variables

cmd open the command line and enter the python command, as shown in the following figure, it is successful:

Then create a new kill360.bat file and enter the following content:

python clean.py

Put it in the working directory along with the .py file

Then open Task Scheduler

Create tasks and configure the process

Then, sit back and relax.

Today's content is shared here, and the editor finally gave a python gift bag [Jiajun Yang: 419693945] to help everyone learn better!

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324341538&siteId=291194637