学习python笔记《python编程快速上手-让繁琐工作自动化》之九

练习题三:
消除缺失的编号
编写一个程序,在一个文件夹中,找到所有带指定前缀的文件,诸如 spam001.txt,spam002.txt 等,并定位缺失的编号(例如存在 spam001.txt 和 spam003.txt,但不存在 spam002.txt)。让该程序对所有后面的文件改名,消除缺失的编号。作为附加的挑战,编写另一个程序,在一些连续编号的文件中,空出一些编号,以便加入新的文件。

def find_numfile(file_path,str_start='新建'):

	file_list=os.listdir(os.path.join(file_path))
	#分解文件名,文件统一前缀名称,数字,文件扩展名
	file=[re.search(r'(\w+)(\d+)(.*)',i).groups() for i in file_list if i.startswith(file_start)]
	#原地按照数字排序
	file.sort(key=lambda x:x[1])
	for i,k in enumerate(file,1):
		old_name=''.join(k)#组合成旧名字
		new_name=re.sub(r'\d+',str(i),old_name)#生成新名字
		#更改名称
		os.rename(os.path.join(file_path,old_name),os.path.join(file_path,new_name))
		print('旧文件名:{} =>> 更改为{}'.format(old_name,new_name))


发布了23 篇原创文章 · 获赞 5 · 访问量 384

猜你喜欢

转载自blog.csdn.net/weixin_43287121/article/details/104487141