需求:从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):