Notes learning python "python programming quick start - let automate the tedious work of" Nine

: Exercise three
to eliminate the missing number
Write a program in a folder to find all files with the specified prefix, such as spam001.txt, spam002.txt, etc., and locate the missing numbers (for example, there spam001.txt and spam003. txt, but there is no spam002.txt). The program allows for all subsequent rename the file, eliminating the number missing. As an additional challenge, write another program, some files consecutively numbered, the number of empty numbers, in order to add a new file.

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))


Published 23 original articles · won praise 5 · Views 384

Guess you like

Origin blog.csdn.net/weixin_43287121/article/details/104487141