日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python桌面文件清理腳本分享_python

作者:小樓夜聽雨QAQ ? 更新時間: 2022-12-14 編程語言

需求

桌面臨時文件較多時,直接刪了不太放心,不刪又顯得很雜亂,故需要寫一個腳本批量清理并備份這些雞肋的文件。

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

1. 可以將桌面文件移動至指定文件夾(可配置)。

2. 可以設置例外文件,比如桌面圖標不需要移動,部分常用的文件也不需要移動。

3. 出現同名文件時,不能直接覆蓋,需要加一個日期后綴予以區分。例如更名為 helloworld-2022-08-30.txt

本來準備按照文件后綴名分文件夾存放的,但畢竟是臨時文件,大概率還是需要定期刪除的,分類后反而不利于檢索。

實現

目錄結構

兩個配置文件,一個主類。

代碼

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

比如需要忽略圖標,可以加上.lnk;需要配置忽略文件夾temp,則在尾行加上temp即可;

location.ini配置需要備份至哪個目錄

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

欄目分類
最近更新