怎么用python批量修改一组文件名?

发布网友

我来回答

1个回答

热心网友

不清楚你的实际文件/情况,仅以问题中的样例/说明及猜测为据;以下代码复制粘贴到记事本,另存为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

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com