用python使文件名按照一定规则批量重命名

Python020

用python使文件名按照一定规则批量重命名,第1张

所用模块:import os

(一)打开文件夹,获得旧文件名

path=r"D:\exp\resultdata"   //文件夹途径

for (root, dirs, files) in os.walk(path):

os.walk(path)//遍历D:\exp\resultdata下文件

(二)获得新文件名(如何打开一个文件)

一般新文件名都保存在一个文件中

new_names_files=open('文件名.txt','r')

content=open('文件名.txt','r')(此时content是一个含有所有new name 的列表)

注意:对新名字(字符串)会有一些操作

(1)对文件名(字符)的分割

用split()进行分割

a=''wer.werrew/"

(2)list 添加新的元素、

用append()进行添加

(3)字典添加新的元素

用update()进行添加

实例:

(三)重命名

利用os.rename()函数

实例:旧名字与新名字的数字相对

file=['1.max','2.max'……]//旧名字

for file in files:

        oldname = os.path.join(root,file)

        namesp=file.split('.')

        new_namesp=d[int(namesp[0])]//数字相对

        newname = os.path.join(root,new_namesp)

        os.rename(oldname,newname)

不清楚你的实际文件/情况,仅以问题中的样例/说明及猜测为据;以下代码复制粘贴到记事本,另存为xx.py

# encoding: utf-8

# Python 3.9.6

import os

import sys

srcfile='./文件名.txt'

dstfolder='D:/ZLSJ'

if not os.path.exists(srcfile):

    print('"%s" does not exist' % srcfile)

    sys.exit()

if not os.path.exists(dstfolder):

    print('"%s" does not exist' % dstfolder)

    sys.exit()

f=open(srcfile, encoding='utf-8')

content=f.readlines()

f.close()

file_list=[]

for file in os.listdir(dstfolder):

    if file.lower().endswith('.txt'):

        file_list.append(file)

n=0

#如果原文件名全部以纯数字命名,则对原文件升序排列

file_list.sort(key=lambda e:int(e[0:-4]))

for file in file_list:

    if n < len(content):

        newname=content[n].strip()

        oldfile=os.path.join(dstfolder, file)

        newfile=os.path.join(dstfolder, newname)

        print('{0} --> {1}'.format(oldfile, newname))

        os.rename(oldfile, newfile)

        n=n+1