使用Python模仿操作系统管理文件夹

要求:

指定文件夹的操作:删除,移动和备份

参考代码:

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2019/06/14 02:25
# @Author  : Shyazhut
# @File    : 文件夹备份.py
# @Project : QinGirl
# @Description: ::  处理一些单反拍摄的照片,因为文件夹里又含有不需要的 psd 文件,所以用代码跑一遍
#                   模仿的是操作系统按照树结构递归对文件进行处理的操作
"""
满足的要求:
指定文件类型进行备份
指定文件类型进行删除等
"""

import os
import re
import time
import shutil
from pyecharts import Line

# 处理的根文件夹
old_root = r"R:\Camera\手机设备(2010"
# 备份存储路径
new_root = r"P:\照片视频备份\手机设备(2010"

FILE_NUM = 0
# 需要删除的文件类型
REMOVE_TYPE = ["123"]

# 忽略备份的文件类型
IGNORE_TYPE = [""]


####################################################################################################################
# 开始处理
def init():
    month_sum = []

    for i in range(0, 12 + 1):
        file_dict = []
        file_dict.append(i)
        file_dict.append(0)
        month_sum.append(file_dict)

    return month_sum


def get_yymmdd(data):
    comp = re.compile("[0-9]+8")
    result = comp.findall(data)[0]

    num = int(result)

    year = str(num // 10000)
    month = int(result.replace(year, "")) // 100
    day = int(result.replace(year, "")) % 100
    year = int(year)

    return year, month, day


def data_processing(datas):
    yy, mm, dd = get_yymmdd(datas)
    return mm


def time_interval(time1, time2):
    interval = time2 - time1
    m, s = divmod(interval, 60)
    h, m = divmod(m, 60)
    standard_time = "spand_time = %d hours %d minutes %d seconds\n" % (h, m, s)
    return standard_time


def log_add(dir, datas):
    """
    写日志函数
    :param dir:处理文件夹 
    :param datas: 写入文本的数据
    :return: 文件
    """
    import time
    time = time.asctime()
    path = dir + "/log_dd.txt"
    fp = open(path, "a+", encoding="utf8")
    adds = []
    adds.append(datas)
    adds.append(time)
    adds = adds[1] + "---" + adds[0] + "\n"
    fp.write(adds)
    fp.flush()
    fp.close()


def deal_file(old_root, new_root, datas):
    """
    处理某个文件
    :param old_root:源文件所在目录 
    :param new_root: 文件的备份目录
    :param datas: 写入文件的日志信息
    :return: mm是次数,未使用
    """
    if not os.path.isfile(datas):
        print(datas + "不是文件!")
        return 0

    mm = 0
    msg = ""

    file_name = os.path.split(datas)[1]
    file_dir = os.path.split(datas)[0]
    file_type = os.path.splitext(file_name)[1]

    if file_type.lower() not in ".psd":
        new_dir = new_root + file_dir.replace(old_root, "")
        if not os.path.exists(new_dir):
            os.makedirs(new_dir)

        new_file = new_dir + r"\\" + file_name
        if not os.path.exists(new_file):
            shutil.copy(datas, new_file)
            notes = " - " + file_name + " saving to " + new_file
            msg = "备份成功"
        else:
            notes = "文件已存在 " + new_file + " 位置"
            msg = "已存在"

    elif file_type.lower() in REMOVE_TYPE:
        os.remove(datas)
        notes = datas + " 文件已删除!"
        msg = "已删除"
    else:
        notes = "未标注处理方式的类型 %s 文件 - " % file_type + datas
        msg = "未处理"
    print(notes)
    notes = file_name + msg
    log_add(new_root, notes)

    return mm


def deal_dir(old_root, new_root, dir):
    """
    递归形式的处理文件夹
    :param old_root: 
    :param new_root: 
    :param dir: 
    :return: 
    """
    if os.path.isfile(dir):
        deal_file(old_root, new_root, dir)

        return

    elif os.path.isdir(dir):
        dir_lists = os.listdir(dir)

        for dir_list in dir_lists:
            deal = dir + r"\\" + dir_list
            deal_dir(old_root, new_root, deal)
    else:
        print("文件不正确 " + dir)


def line_chart(data_save):
    """
    图片信息的可视化,似乎没做
    :param data_save: 
    :return: 
    """
    names = []
    highs = []
    for i in range(1, len(data_save[0])):
        names.append(data_save[0][i][0])
        highs.append(data_save[0][i][1])
    line = Line("wq河南本科教学评估分数折线图", '2016年度wqs', width=1200, height=600)
    line.add("分数", names, highs, mark_point=['max'], is_datazoom_show=True, is_fill=None, line_opacity=0.520,
             area_opacity=0.13)

    line.render(f"wenqin_line.html")


def main():
    time1 = time.time()
    deal_dir(old_root, new_root, old_root)
    time2 = time.time()
    print("文件夹处理完成!日志文件已存储在 " + new_root)
    log = time_interval(time1, time2) + "\n**********************************\n\n"
    log_add(new_root, log)

    print(log)


if __name__ == '__main__':
    main()

 

你可能感兴趣的:(摄影,Python)