File classification, move and rename operations

file classification

Second lesson on learning python

Questions are as follows:
1.os and os.path operations

Put mnist_train/datasetthe files in the folder into mnist_trainthe corresponding folder according to the label, remove the label and add the mnist_train_prefix, for example, 1_1.pngchange it to mnist_train_1.pngand put the file mnist_tarin/1in the folder, and submit the code for the job.

Significance: Strengthen the further understanding of the path, and be familiar with the operation of the file.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-hhwI3XTK-1605323274561) (C:\Users\rui\Pictures\Typora\QQ screenshot 20201114100635.png)]

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-uyCpbwjV-1605323274563) (C:\Users\rui\Pictures\Typora\QQ screenshot 20201114100821.png)]

Title description: The general meaning is to classify each number from the dataset into 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 folders, and rename them

code show as below:
import os
rootpath = "D:\\I\\college\\artificial intelligence\\os&&opencv\\mnist_train"
root1 = "D:\\I\\college\\artificial intelligence\\os&&opencv\\mnist_train\\dataset"
list1 = os.listdir(rootpath)
for dir_name in list1:  #在list1中调用dir_name
	for file_name in os.listdir(os.path.join(rootpath, dir_name)):		 #将dir_name与rootpath合并,并返回给file_name
		temp = file_name.split('.',1)[0]		#分离file_name中文件的文件名与后缀名,并把文件名赋给temp
		name1 = temp.split('_',1)[0]
		name2 = temp.split('_',1)[1]			#分离temp中文件的文件名,根据_的前后分离,并将前面赋给name1,后面赋给name2
		print (os.path.join(root1, file_name) + "\t\t" + os.path.join(rootpath, name2, 'mnist_train_' + name1 + ".png"))
		os.rename(os.path.join(root1, file_name), os.path.join(rootpath, name2,  'mnist_train_' + name1 + ".png"))	#重命名
operation result:

As shown in the picture: all the 0s in the dataset folder have entered the 0 folder, and the rest of the numbers are the same, so there is nothing in datast.

Insert image description here

おすすめ

転載: blog.csdn.net/weixin_51654869/article/details/109687970