移动文件到另一个目录下

移动文件到另一个目录下(可指定后缀,指定文件名)

代码示例:

import os
import shutil


def is_exists(file_exs, file_ex):
    """
    是否存在里面
    :param file_exs: 后缀列表
    :param file_ex: 后缀
    :return:
    """
    for i in file_exs:
        if i in file_ex:
            return True
        else:
            return False


def move_to_file(old_path, new_path, file_ex, filename=None):
    """
    移动文件到另一个路径下
    :param old_path: 旧路径
    :param new_path: 新路径
    :param file_ex: 后缀 列表
    :param filename: 文件名 列表
    :return: 新路径列表
    """
    files = os.listdir(old_path)
    lis_file = []
    for file in files:
        ex = os.path.splitext(file)[-1]  # 获取文件后缀
        if ex in file_ex or is_exists(file_ex, ex):
            if filename is None:
                new_file = move_file(file=file, ex=ex, old_path=old_path, new_path=new_path)
                lis_file.append(new_file)
            else:
                for name in filename:
                    if name in file or file in name:
                        new_file = move_file(file=file, ex=ex, old_path=old_path, new_path=new_path)
                        lis_file.append(new_file)
    return lis_file


def move_file(file, ex, old_path, new_path):
    """
    移动文件
    :param file: 文件路径
    :param ex: 文件后缀
    :param old_path: 旧路径
    :param new_path: 新路径
    :return: 新文件路径
    """
    name, suffix = file.rsplit(ex)
    name = name.replace('.', '')
    old_name = os.path.join(old_path, file)
    new_name = os.path.join(new_path, ''.join([name, ex]))
    shutil.copyfile(old_name, new_name)
    return new_name


if __name__ == '__main__':
    old_path = r"C:\Users\14486\Desktop\123"
    new_path = r'C:\Users\14486\Desktop\46'
    file_ex = ['.xlsx', '.txt']
    filename = ['新建', '工作计划']
    files = move_to_file(old_path=old_path, new_path=new_path, file_ex=file_ex, filename=filename)
    print(files)
"""
['C:\\Users\\14486\\Desktop\\46\\工作计划.txt', 'C:\\Users\\14486\\Desktop\\46\\新建 XLSX 工作表.xlsx']
"""
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页