Python同目录文件批量重命名

时间:2021-11-10 13:24:43
import os, os.path

'''**************************************************************************
根据src_dir的文件重命名dest_dir目录下的文件, src_dir与dest_dir文件数最好相同
***************************************************************************'''

def RenameDir(src_dir, dest_dir):

dest_file_list = os.listdir(dest_dir)

i = 0
for file in os.listdir(src_dir):
source_file = os.path.join(src_dir, file)


dest_file = os.path.join(dest_dir, dest_file_list[i])
print(dest_file)
i = i + 1

os.rename(dest_file, dest_dir + file)

'''**************************************************************************
自动填充文件名, eg: “小破孩.mp4” -> "小破孩0001.mp4"
***************************************************************************'''

def AutoFillFileName(src_dir):
i = 0
for file in os.listdir(src_dir):
#if have desktop.ini skip it, it is windows hide file
if file == r'desktop.ini' :
continue

i = i + 1

#fill 填充字符
#align '>'填充右边 '<'填充左边 '^'填充两边
#5 填充个数
fill_str = '{0:{fill}{align}5}'.format(i, fill=0, align=r'>')

source_file = os.path.join(src_dir, file)
if os.path.exists(source_file) is False:
print(source_file + r' : is not exist')
base_name = os.path.splitext(file)[0]
suffix = os.path.splitext(file)[1]
new_name = base_name + fill_str + suffix

dest_file = source_dir + new_name
print(dest_file)
os.rename(source_file, dest_file)

'''**************************************************************************
截取文件名, eg: “小破孩0001.mp4” -> "小破孩.mp4"
***************************************************************************'''

def SubFileName(src_dir):
for file in os.listdir(source_dir):
#if have desktop.ini skip it, it is windows hide file
if file == r'desktop.ini' :
continue

source_file = os.path.join(source_dir, file)
if os.path.exists(source_file) is False:
print(source_file + r' : is not exist')

base_name = os.path.splitext(file)[0]
#删除base_name最后5个字符
base_name = base_name[:-5]

suffix = os.path.splitext(file)[1]
new_name = base_name + suffix

dest_file = source_dir + new_name
print(dest_file)
os.rename(source_file, dest_file)


'''**************************************************************************
main
***************************************************************************'''

if __name__ == '__main__':

CopyDir(r'E:/新建文件夹/', r'E:/新建文件夹1/')
#RenameDir(r'E:/新建文件夹/', r'E:/新建文件夹1/')

source_dir = r'E:/新建文件夹1/'
if os.path.exists(source_dir) is False:
source_dir = os.path.dirname(__file__) + r'/'
print(source_dir)

#AutoFillFileName(source_dir)
#SubFileName(source_dir)