I wrote a small tool in Python, no matter how complicated the folder is, I will help you organize it in minutes, and use it immediately

sucks

I admit that I am not a person who likes to organize the desktop, because I feel that the cluttered desktop is easy to find files.

Haha, but the desktop is so messy recently that I can't watch it anymore, and it almost fills the entire screen. Although there are many softwares to organize the desktop with one click, I also need to organize the files in other paths, so I thought of using Python to complete this requirement.

insert image description here

Show results

I divided the files into 9 categories in total, namely pictures, videos, audios, documents, compressed files, common formats, program scripts, executable programs and font files.

# 不同文件组成的嵌套字典
file_dict = {
    
    
            '图片': ['jpg','png','gif','webp'],
            '视频': ['rmvb','mp4','avi','mkv','flv'],
            "音频": ['cd','wave','aiff','mpeg','mp3','mpeg-4'],
            '文档': ['xls','xlsx','csv','doc','docx','ppt','pptx','pdf','txt'],
            '压缩文件': ['7z','ace','bz','jar','rar','tar','zip','gz'],
            '常用格式': ['json','xml','md','ximd'],
            '程序脚本': ['py','java','html','sql','r','css','cpp','c','sas','js','go'], 
            '可执行程序': ['exe','bat','lnk','sys','com'],
            '字体文件': ['eot','otf','fon','font','ttf','ttc','woff','woff2']
        }

file_dict is a dictionary defined by itself, which contains the formats commonly used in our study and work. The common format needs to be explained to everyone. For the files that are often used but do not know which type of files they are placed in, they are all stored here.

Note : If you have other file formats on your computer, just modify the above file_dict dictionary .

development ideas

The development of such a small tool involves a total of three Python libraries, namely the os module, the shutil module, and the glob module . They are used together to process files and folders, which is simply super powerful!

The whole development steps, the general idea is as follows:

  • ① Any given file path;
  • ② Get all the files under the current file path, and get the suffix corresponding to each file;
  • ③ Determine whether each file is in the specified nested dictionary, and return the corresponding file classification;
  • ④ Determine whether the folder of each file classification exists. Because you need to create a new folder for classifying and storing files;
  • ⑤ Copy each file to the corresponding category;

The complete code is as follows:

# 导入相关库
import os
import glob
import shutil

# 采用input()函数,动态输入要处理的文件路径。
path = input("请输入要清理的文件路径:")

# 定义一个文件字典,不同的文件类型,属于不同的文件夹,一共9个大类。
file_dict = {
    
    
            '图片': ['jpg','png','gif','webp'],
            '视频': ['rmvb','mp4','avi','mkv','flv'],
            "音频": ['cd','wave','aiff','mpeg','mp3','mpeg-4'],
            '文档': ['xls','xlsx','csv','doc','docx','ppt','pptx','pdf','txt'],
            '压缩文件': ['7z','ace','bz','jar','rar','tar','zip','gz'],
            '常用格式': ['json','xml','md','ximd'],
            '程序脚本': ['py','java','html','sql','r','css','cpp','c','sas','js','go'], 
            '可执行程序': ['exe','bat','lnk','sys','com'],
            '字体文件': ['eot','otf','fon','font','ttf','ttc','woff','woff2']
        }

# 定义一个函数,传入每个文件对应的后缀。判断文件是否存在于字典file_dict中;
# 如果存在,返回对应的文件夹名;如果不存在,将该文件夹命名为"未知分类"
def func(suffix):
    for name, type_list in file_dict.items():
        if suffix.lower() in type_list:
            return name
    return "未知分类"

# 递归获取 "待处理文件路径" 下的所有文件和文件夹。
for file in glob.glob(f"{path}/**/*",recursive=True):
 # 由于我们是对文件分类,这里需要挑选出文件来。
    if os.path.isfile(file):
     # 由于isfile()函数,获取的是每个文件的全路径。这里再调用basename()函数,直接获取文件名;
        file_name = os.path.basename(file)
        suffix = file_name.split(".")[-1]
        # 判断 "文件名" 是否在字典中。
        name = func(suffix)
        #print(func(suffix))
        # 根据每个文件分类,创建各自对应的文件夹。
        if not os.path.exists(f"{path}\\{name}"):
            os.mkdir(f"{path}\\{name}")
        # 将文件复制到各自对应的文件夹中。
        shutil.copy(file,f"{path}\\{name}")  

The result is as follows:

insert image description here

Outlook

The purpose of learning Python is to solve problems, so I have always advocated learning with practical cases.

But on the other hand, when you see a fun case, you can't just run it, but learn its implementation principles and related Python knowledge. Only then can you solve more problems and solve problems unique to you.

So I hope everyone can combine the two, so that we can go further and better!

Recommended reading

The roommate who sleeps in my upper bunk uses python to earn my living expenses for one semester in a month

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326829792&siteId=291194637