网络编程
位置:首页>> 网络编程>> Python编程>> Python桌面文件清理脚本分享

Python桌面文件清理脚本分享

作者:小楼夜听雨QAQ  发布时间:2022-10-11 03:13:23 

标签:Python,桌面文件,清理

需求

桌面临时文件较多时,直接删了不太放心,不删又显得很杂乱,故需要写一个脚本批量清理并备份这些鸡肋的文件。

所以脚本需要具有以下功能

1. 可以将桌面文件移动至指定文件夹(可配置)。

2. 可以设置例外文件,比如桌面图标不需要移动,部分常用的文件也不需要移动。

3. 出现同名文件时,不能直接覆盖,需要加一个日期后缀予以区分。例如更名为 helloworld-2022-08-30.txt

本来准备按照文件后缀名分文件夹存放的,但毕竟是临时文件,大概率还是需要定期删除的,分类后反而不利于检索。

实现

目录结构

两个配置文件,一个主类。

Python桌面文件清理脚本分享

代码

ignore.ini配置需要忽略的文件名或者后缀名。

比如需要忽略图标,可以加上.lnk;需要配置忽略文件夹temp,则在尾行加上temp即可;

Python桌面文件清理脚本分享

location.ini配置需要备份至哪个目录

Python桌面文件清理脚本分享

main.py主类

import os
import datetime
import shutil

def get_config(file_name):
   """
   读取配置文件
   :param file_name: 文件名
   :return: 按行读取
   """
   f = open(file_name)
   lines = []
   for line in f.readlines():
       line = line.strip('\n')
       lines.append(line)
   return lines

def get_desktop():
   """
   获取桌面路径
   :return: 桌面绝对路径
   """
   return os.path.join(os.path.expanduser("~"), 'Desktop')

def get_suffix(dir_path):
   """
   获取文件的后缀名
   :param dir_path: 文件名
   :return: 后缀名
   """
   return os.path.splitext(dir_path)[-1]

def get_exclude_suffix():
   """
   获取不参与整理的文件后缀名
   """
   dirs = {}
   lines = get_config('ignore.ini')
   for line in lines:
       dirs.setdefault(line, 0)
   return dirs

def get_target_path():
   """
   备份至指定文件夹
   :return: 目标位置的路径
   """
   return get_config('location.ini')[0]

def get_source_dirs():
   """
   获取需要转移的文件
   :return: 文件目录
   """
   dirs = os.listdir(get_desktop())
   suffixes = get_exclude_suffix()
   fit_dirs = []
   for dir in dirs:
       suffix = get_suffix(dir)
       if suffix not in suffixes and dir not in suffixes:
           fit_dirs.append(dir)
   return fit_dirs

def get_time():
   """
   获取当前年月日
   :return: 时间
   """
   return datetime.datetime.now().strftime('-%Y-%m-%d')

def get_rename(path):
   """
   文件重命名
   :param path: 路径
   :return: 命名后的路径
   """
   if os.path.isdir(path):
       return path + get_time()
   else:
       return os.path.splitext(path)[0] + get_time() + get_suffix(path)

def move():
   """
   移动文件
   """
   dirs = get_source_dirs()
   target_base_path = get_target_path()
   desk_url = get_desktop()
   if not os.path.exists(target_base_path):
       os.makedirs(target_base_path)

for dir in dirs:
       path = os.path.join(desk_url, dir)
       target_path = os.path.join(target_base_path, dir)
       if os.path.exists(target_path):
           # 如果有同名文件,则加一个日期后缀
           target_path = get_rename(target_path)
       shutil.move(path, target_path)

if __name__ == '__main__':
   move()

直接  python main.py 执行脚本即可

来源:https://blog.csdn.net/qq_37855749/article/details/126596680

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com