消除缺失的编号

编写一个程序,在一个文件夹中,找到所有带指定前缀的文件,诸如 spam001.txt,spam002.txt 等,并定位缺失的编号(例如存在 spam001.txt 和 spam003.txt,但不存在 spam002.txt)。让该程序对所有后面的文件改名,消除缺失的编号。

import shutil, os

for folderName, subfolders, filenames in os.walk('.'):
	counter = 1
	container = []

	for filename in filenames:
		if filename.startswith('spam'):
			container.append(filename)
	container.sort()
	
	for item in container:
		temp = 'spam' + str(counter).rjust(3, '0') + '.txt'
		
		if item != temp:
			print(f"CHANGE FILE NAME {item} to {temp}")
			item = os.path.abspath('.') + '\\' + folderName + '\\' + item
			temp = os.path.abspath('.') + '\\' + folderName + '\\' + temp
			shutil.move(item, temp)
		counter += 1
		

猜你喜欢

转载自blog.csdn.net/dongyu1703/article/details/81952631