腾讯良心软件,被秒了

程序员宝藏库GitHub - Jackpopc/CS-Books-Store: 你想要的计算机经典书籍,这里都有!

欢迎大家添加vx:code_7steps和我进行技术交流!

在使用电脑的时候,我一直有个困扰,每次下载的文件都会默认选择一个文件夹,例如Downloads

任何种类的文件都混在那个文件夹里。

你有同样的问题吗?

如果你的回答是肯定的,那么,本文一定会对你起到一定的作用。

准备工作

我的文件有三个类别,取决于扩展名,如果你有自己的类别,可以继续添加:

  • 文件(.pdf、.docx、和.txt)

  • 音频(.m4a、.m4b和.mp3)

  • 图片 (.jpg, .jpeg, 和 .png)

然后,我想把每个文件移到一个具有预定义类别的文件夹中。

看到这里,关注平凡而诗意的同学应该知道,很久之前我分享过腾讯一款名为DeskGo的软件,可以实现这项功能,DeskGo也算得上腾讯难得的良心产品。

但是,或许很多同学并不是喜欢腾讯系软件臃肿、吃相难看的样子。

因此,本文就动手自己开发一款专属,而且更加好用的DeskGo

开发

导入模块ospathlib,对路径、文件和目录进行操作。

import os
from pathlib import Path

用你在准备工作中的清单,使用字典格式定义文件类别:

SUBDIR = {
        "DOCUMENTS":[".pdf",".docx",".txt"],
        "AUDIO":[".m4a",".m4b",".mp3"],
        "IMAGES":[".jpg",".jpeg",".png"]
        }

如果你想满足自己个性化的需求,你只需要把key-value修改成对应的文件类型-扩展名即可。

从已知的扩展名中挑选类别名称的功能。只需循环并检查你的文件扩展名,然后返回类别:

def pickDir(value):
    for category, ekstensi in SUBDIR.items():
        for suffix in ekstensi:
            if suffix == value:
                return category

下面是主函数部分:

def organizeDir():
    for item in os.scandir():
                
        if item.is_dir():
                continue
                
        filePath = Path(item)
        fileType = filePath.suffix.lower()
        directory = pickDir(fileType)
        
        if directory == None:
            continue
        
        directoryPath = Path(directory)
        if directoryPath.is_dir() != True:
                directoryPath.mkdir()
        filePath.rename(directoryPath.joinpath(filePath))

调用organizationDir函数:

organizeDir()

运行

下面,就来运行代码,对比一下效果。

整理前

整理后

下面是完整的代码:

import os
from pathlib import Path
​
​
SUBDIR = {
        "DOCUMENTS":[".pdf",".docx",".txt"],
        "AUDIO":[".m4a",".m4b",".mp3"],
        "IMAGES":[".jpg",".jpeg",".png"]
        }
​
def pickDir(value):
    for category, ekstensi in SUBDIR.items():
        for suffix in ekstensi:
            if suffix == value:
                return category
​
def organizeDir():
    for item in os.scandir():
                
        if item.is_dir():
                continue
                
        filePath = Path(item)
        fileType = filePath.suffix.lower()
        directory = pickDir(fileType)
        
        if directory == None:
            continue
        
        directoryPath = Path(directory)
        if directoryPath.is_dir() != True:
                directoryPath.mkdir()
        filePath.rename(directoryPath.joinpath(filePath))
​
if __name__ == '__main__':
  organizeDir()

感兴趣的同学,赶快试一下吧!


大家好,我是Jackpop!我花费了半个月的时间把这几年来收集的各种技术干货整理到一起,其中内容包括但不限于Python、机器学习、深度学习、计算机视觉、推荐系统、Linux、工程化、Java,内容多达5T+,获取方式:技术干货_免费高速下载|百度网盘-分享无限制(提取码:0000)

猜你喜欢

转载自blog.csdn.net/jakpopc/article/details/122676604