admin 管理员组

文章数量: 887006

安卓手机在读取U盘时会自动创建Android,Sounds等文件夹,弹出U盘后,这些文件夹本身可以删除。但是这些文件夹数量比较多,假如U盘根目录下的文件夹又比较多,每次手动删除就会很麻烦,且有误删的风险。

这个python脚本,可以实现自动删除这些文件夹:

⚠注意:由于包含删除文件及文件夹的破坏性操作,请评估风险后慎重操作。推荐在使用此脚本前先在新建的文件夹下测试一遍,且在第一次操作前先做好备份。

"""
After opening a udisk on android mobile device,\n
system would auto create several useless files and directories.\n
This python script could help clean up your udisk.\n
---
REMIND THIS:\n
Make sure the fileames of your own files&dirs are stored in the set 'verified_items'.\n
This script would delete all files&dirs except those included in 'verified_items'\n
Think twice before you run this script.
"""
import os
import shutil

config_file = "ignore.config" # path of config file that stores verified files&dirs
verified_items = {os.path.basename(__file__), config_file, "System Volume Information"} # verified files&dirs
"""verified files&dirs: Filenames of your own files&dirs is stored in this set"""

def update_verified_items():
    global verified_items
    try: # read verified files&dirs from config file
        with open(config_file,"r") as f:
            for line in f.readlines():
                verified_items.add(line.strip('\n'))
    except FileNotFoundError: # use default value
        verified_items = {os.path.basename(__file__), config_file, "System Volume Information", "library", "misc", "untrusted"} # default value
    return

def create_del_list(path: str):
    """compare files&dirs under the path given with the items in 'verified_items',\n\n\
        and return all the files&dirs not needed, stored in a set"""
    return set(os.listdir(path)).difference(verified_items)

def main():

    os.chdir(os.path.dirname(__file__))
    wd = os.getcwd()
    update_verified_items()
    items_to_be_deleted = create_del_list(wd)

    # return if no invalid files&dirs found
    if items_to_be_deleted == set():
        print("working directory clean, nothing to delete.")
        return
    # double check before execute deleting
    print("""
⚠  REMIND THIS: ⚠
Make sure the fileames of ALL YOUR OWN FILES&DIRS are stored in the set 'verified_items'.
This script would delete all these files&dirs:
          """)
    for items in items_to_be_deleted:
        print(items)
    flag = input("\nRUN SCRIPT AND DELET THESE FILES AND DIRECTORIES?[y/N]") == "y"
    if not flag:
        print("Deletion aborted by user.")
        return

    # execute deleting
    for item in items_to_be_deleted:
        if (os.path.isdir(item)):
            shutil.rmtree(item)
            continue
        if (os.path.isfile(item)):
            os.remove(item)
    print("\nCOMPLETE !")

# try the main function here:
main()

- 由于删除文件是破坏性操作,安全起见保留了二次确认模块,在删除无用文件前需要做一次确认。

- 为方便后续调用和修改,使用了main函数。引用的情况下把最后面的main函数调用注释掉就好。

- 考虑到U盘根目录的文件夹很多的情况,增加了配置文件接口。检测到配置文件"ignore.config"(如果不想用这个文件名,可以在最前面的初始化config_file变量这里赋其他的值)时,变量verified_items使用config文件给出的忽略文件夹列表,配置文件不存在时则使用脚本内给定的默认值(可以在定义update_verified_items函数的那边修改)。

- 脚本可以用VSCode等IDE打开后运行,可以自己写一个bat脚本调用,也可以在命令行里调用python.exe运行

- 平时使用U盘增删文件时,尽可能地在非根目录下进行;如有在根目录下保存了新的文件或文件夹,请及时修改配置文件,或者修改代码里的verified_items默认值。

重申一遍,由于包含删除文件及文件夹的破坏性操作,请评估风险后慎重操作。推荐在使用此脚本前先在新建的文件夹下测试一遍,且在第一次操作前先做好备份。

本文标签: 脚本 文件夹 文件 手机 python