在日常工作和生活中,我们经常要复制和重命名文件,如果遇到大量数据处理时,手动去操作非常麻烦,现在我们可以通过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))