【Python】shutil內置模塊複製和重命名文件

在日常工作和生活中,我們經常要複製和重命名文件,如果遇到大量數據處理時,手動去操作非常麻煩,現在我們可以通過python的shutil模塊完成,以下主要介紹幾種場景:
1.複製一個文件到其他目錄,不重新命名;
2.複製一個文件到其他目錄,重新命名;
3.複製某個固定文件,生成N個重命名的新文件;
4.複製某個文件夾中多個文件,到其他目錄、不重新命名;
5.複製某個文件夾中多個文件,到其他目錄、重新命名;

# -*- coding: utf-8 -*-
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#作者:cacho_37967865
#博客:https://blog.csdn.net/sinat_37967865
#文件:rename_file.py
#日期:2020-05-02
#備註: 批量對文件進行重命名、批量複製文件
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

import os
import shutil
from pythonlession.basefunction.get_all_file import get_files
from pythonlession.basefunction.deal_file import get_file,save_file


# 複製某個文件:sample-原始文件、new_path-新文件目錄
def copy_file(sample,new_path):
    if not os.path.exists(new_path):
        os.makedirs(new_path)
    new_file = os.path.join(new_path, os.path.basename(sample))
    shutil.copy(sample, new_file)
    print('複製後的文件完整路徑:',new_file)
    return new_file

# 複製某個文件並重命名:sample-原始文件、new_path-新文件目錄、file_name-新文件名稱
def copy_rename_file(sample,new_path,file_name):
    if not os.path.exists(new_path):
        os.makedirs(new_path)
    new_file = os.path.join(new_path, file_name)
    shutil.copy(sample, new_file)
    print('複製並重命名後的文件完整路徑:',new_file)
    return new_file

# 複製某個文件生成多個重命名文件:sample-原始文件、new_path-新文件目錄、num-生成數量
def copy_n_files(sample,new_path,num):
    if not os.path.exists(new_path):
        os.makedirs(new_path)
    for i in range(num):
        new_file = os.path.join(new_path, '%03d_'%(i) + os.path.basename(sample))
        shutil.copy(sample, new_file)
        print('複製並重命名後的文件完整路徑:',new_file)

# 複製多個文件到其他目錄:
def copy_files(file_path,file_type,new_path):
    if not os.path.exists(new_path):
        os.makedirs(new_path)
    files = get_files(file_path, file_type)
    for file in files:
        new_file = os.path.join(new_path, os.path.basename(file))
        shutil.copy(file, new_file)
        print('複製後的文件完整路徑:', new_file)


# 複製多個文件到其他目錄並且重命名:方法一
def copy_rename_files(file_path,file_type,new_path):
    if not os.path.exists(new_path):
        os.makedirs(new_path)
    files = get_files(file_path, file_type)
    for i in range(len(files)):
        file = files[i]
        new_file = os.path.join(new_path, '%03d_'%(len(files)-i) + os.path.basename(file))
        shutil.copy(file, new_file)
        print('複製並重命名後的文件完整路徑:', new_file)

#  複製多個文件到其他目錄並且重命名:方法二
def rename_files(file_path,type,new_path):
    if not os.path.exists(new_path):
        os.makedirs(new_path)
    files = get_files(file_path, type)
    for i in range(len(files)):
        file = files[i]
        new_file = os.path.join(new_path, '%03d_'%(len(files)-i) + os.path.basename(file))
        byte_file = get_file(file)         # 二進制方式打開
        save_file(new_file,byte_file)      # 二進制方式存儲
        print('重命名前的文件爲:%s,重命名後文件爲:%s' %(file,new_file))

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章