Pythonは、複数のフォルダーからファイルをランダムに取得して、他のパスにコピーします



Python Randomly Get Files From Multiple Folders Copy Other Path



タイトルの通り、手作業でコピー&ペーストできれば問題ありませんでした。流行の状況で家にいるのが退屈すぎるのはなぜですか。さらに、モデル検証スクリプトのデータセットのランダムな選択として使用したいので、このプログラムを作成しました。このブログも退屈で、私はしません。私が何をしているのか知っています。書くだけ。

私がやりたいのは、下のフォルダからランダムに2つの写真を選択し、他のパスにコピーすることです



import os, random, shutil firstdir ='C:/Users/10791/Desktop/data set/ExDark/'#The path of the file to be copied tardir ='D:/Anaconda/pycode/test/'# Path to copy to pathdir = os.listdir(firstdir)#Get all files in the path path1 = pathdir[:-1]#Here I don’t need the last folder, remove it #Combine the path and folder name together path = [] for path2 in path1: path.append(firstdir + path2) k = 0# is used as the folder name, which is the key of the image category for i in path: j = 0#Because it cannot be named repeatedly, add a j after the file name to distinguish sample = random.sample(os.listdir(i), 2)# randomly select 2 pictures from each category folder for name in sample:#Copy and rename each selected file j += 1 cut = name.split('.')#Because the file suffix is ​​different, here we use split to get the file suffix name shutil.move(i+'/'+name, tardir+'/'+name)#Copy operation os.rename(tardir+'/'+name,tardir+'/'+path1[k]+str(j)+'.'+cut[1])# Rename to the first few of the category (path1[k]) (J) Picture. Suffix (cut[1]) k += 1

結果は次のとおりです。