桌面文件整理

本文介绍了一个Python脚本,用于在桌面路径下创建并管理不同类型的文件夹,如文本、执行文件、图像等,并将文件自动移动到相应的文件夹中,避免同名文件冲突,最后删除空文件夹。
摘要由CSDN通过智能技术生成

 感觉还蛮好用的:)

2024/2/26:生成文件夹没有文件则删除该文件夹

import os
import shutil
from pathlib import Path

# 桌面路径
desktop_path = Path(r"D:\yzzob\Desktop")

# 创建存放不同类型文件的文件夹
folders = {
            "txt": "TextFiles",
            "exe": "ExecutableFiles",
            "jpg""png": "ImageFiles",
            "png": "ImageFiles",
            "xlsx": "DocFile",
            "docx": "DocFile",
            "pcap": "CtfAttachments",
            "pcapng": "CtfAttachments",
            "":"CtfAttachments",
            "raw":"CtfAttachments",
            "til":"IdaFile",
            "id0":"IdaFile",
            "nam":"IdaFile",
            "id1":"IdaFile",
            "id2":"IdaFile"
           }

for folder_name in folders.values():
    folder_path = desktop_path / folder_name
    folder_path.mkdir(exist_ok=True)

# 移动文件到对应的文件夹
for file_path in desktop_path.iterdir():
    if file_path.is_file():
        file_extension = file_path.suffix.lower()[1:]
        if file_extension in folders:
            destination_folder = desktop_path / folders[file_extension]
            target_path = destination_folder / file_path.name
            # 检查目标路径是否存在同名文件
            if target_path.exists():
                # 重命名文件
                current_date = datetime.datetime.now().strftime("%Y%m%d_%H_%M_%S")
                new_name = file_path.stem + "_" + current_date + file_path.suffix
                target_path = destination_folder / new_name
            shutil.move(str(file_path), str(target_path))

# 删除空文件夹
for folder_name in folders.values():
    folder_path = desktop_path / folder_name
    if folder_path.exists():
        if not any(folder_path.iterdir()):
            folder_path.rmdir()

  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值