背景需求
下载教程,手动输入编号,有一个编号错误,导致后面所有编号都错了。30实际是29,以此类推
怎样才能快速修改编号数字?

前期考虑到可能要改编号,所以在每个编号后面加“ ”(空格),并保证文件名其他位置没有空格

用代码先在编号文件名前面 再加一个“29 ”的编号,判断添加顺序是否正确(万一有搞错项目的情况发生。)
import os
import time
path =r"D:\test\iVX\12 官网教程\04 营销互动(改编号)"
# UI搭建
a=29
fileList=os.listdir(path)
for file in fileList:
# split_str = file.split(' ')
# newname1 = split_str[0] # _的第0部分=序号
# newname2= split_str[1] # _的第0部分=序号
# newname=newname1+'mp4'
newname='{} '.format(a)+file
oldname_path = os.path.join(path,file)
# 文件新路径
newname_path = os.path.join(path,newname)
# 新旧对调
os.rename(oldname_path, newname_path)
a+=1
结果可以看到,左边的新编号与右边的错误号码差一位,说明新序号正确

再把文件名里面的第二个号码删除
import os
import time
path =r"D:\test\iVX\12 官网教程\04 营销互动(改编号)"
# UI搭建
fileList=os.listdir(path)
for file in fileList:
split_str = file.split(' ')
newname1 = split_str[0] # _的第0部分=序号
newname2= split_str[2] # _的第0部分=序号
# newname=newname1+'mp4'
newname=newname1+' '+newname2
oldname_path = os.path.join(path,file)
# 文件新路径
newname_path = os.path.join(path,newname)
# 新旧对调
os.rename(oldname_path, newname_path)

用同样的方法修改其他编号。顺利获得正确号码




运行两个代码有点麻烦。可以把两个代码组合在一起。

import os
import time
path =r"D:\test\iVX\12 官网教程\\09 连接"
a=81
fileList=os.listdir(path)
for file in fileList:
split_str = file.split(' ') #空格作为分割点,提取1
newname1 = split_str[1] # _的第1部分=序号
newname='{} '.format(a)+newname1
# 删除了错误的序号,前面加上正确的序号空格
oldname_path = os.path.join(path,file)
# 文件新路径
newname_path = os.path.join(path,newname)
# 新旧对调
os.rename(oldname_path, newname_path)
a+=1

问题:发现中间有两个空格


path =r"D:\test\iVX\12 官网教程\kong"
fileList=os.listdir(path)
for file in fileList:
split_str = file.split(' ')
newname1 = split_str[0] # _的第0部分=序号
print(newname1)
newname2= split_str[2] # _的第0部分=序号
print(newname2)
newname=newname1+' '+newname2
oldname_path = os.path.join(path,file)
# 文件新路径
newname_path = os.path.join(path,newname)
# 新旧对调
os.rename(oldname_path, newname_path)


空格一样大小(1个空格)
重要提示:
不能保证程序正确时,最好把数据备份

否则如果改名失败,文件名上的所有的信息都会被删除,无法恢复
