需求:從input文件夾中隨機獲取一定數量的jpg文件復制到output文件夾中,
如果input文件夾中有與選中的jpg文件文件名相同的ans文件則復制到output文件夾中
參考網頁地址:
https://blog.csdn.net/weixin_40769885/article/details/82869760
https://blog.csdn.net/u010167269/article/details/51084312
https://blog.csdn.net/u010454261/article/details/80903804
代碼:
1 #!/usr/bin/env python 2 # encoding: utf-8 3 4 import os, random, glob 5 from shutil import copyfile 6 7 8 #定義要處理的文件夾變量 9 #choseImg是隨機選中的jpg文件文件名包括后綴 10 choseImg = [] 11 12 def copyFile(inputDir, outDir, count): 13 #通過glob.glob來獲取原始路徑下,所有'.jpg'文件 14 imageList1 = glob.glob(os.path.join(inputDir, '*.jpg')) 15 #隨機獲取count數量的jpg文件 16 imageRandom = random.sample(imageList1, count) 17 18 #遍歷所有隨機得到的jpg文件,獲取文件名稱(包括后綴) 19 for item in imageRandom: 20 choseImg.append(os.path.basename(item)) 21 22 #os.path.splitext(),返回元組,為文件名稱與文件后綴格式 23 for item in choseImg: 24 #將隨機選中的jpg文件遍歷復制到目標文件夾中 25 copyfile(inputDir+'/'+item, outDir+'/'+item) 26 27 #更改jpg文件后綴為ans 28 (temp1, temp2) = os.path.splitext(item) 29 temp = temp1 + '.ans' 30 if os.path.exists(inputDir+'/'+temp): 31 #將ans文件遍歷復制到目標文件夾中 32 copyfile(inputDir+'/'+temp, outDir+'/'+temp) 33 return 34 35 if __name__ == '__main__': 36 inputfile = input('請輸入原始路徑(如:E:/input/):') 37 outfile = input('請輸入目標路徑(如:E:/output/):') 38 count = int(input('請輸入隨機選取的數量(如:3):')) 39 #指定找到文件后,另存為的文件夾路徑 40 outDir = os.path.abspath(outfile) 41 #指定文件的原始路徑 42 inputDir = os.path.abspath(inputfile) 43 copyFile(inputDir, outDir, count)
出現的錯誤:
1.
inconsistent use of tabs and spaces in indentation
解決辦法:重新調整代碼縮進,每次縮進都使用8個space
2.沒有判斷ans文件是否在目錄中存在
增加判斷: if os.path.exists(inputDir+'/'+temp):