python實現從文件夾隨機拷貝出指定數量文件到目標文件夾


為了方便倒騰數據,功能如題,該腳本和操作目錄在同一根目錄

實際運行時要手動修改程序中:cpfile_rand('img', 'outfile', 10) # 操作目錄,輸出目錄,輸出數量

import os
import random
import shutil

def cpfile_rand(img, outfile, num):
    list_ = os.listdir(img)
    if num > len(list_):
        print('輸出數量必須小於:', len(list_))
        exit()
    numlist = random.sample(range(0,len(list_)),num) # 生成隨機數列表a
    cnt = 0
    for n in numlist:
        filename = list_[n]
        oldpath = os.path.join(img, filename)
        newpath = os.path.join(outfile, filename)
        shutil.copy(oldpath, newpath)
        print('剩余文件:', num-cnt)
        cnt = cnt + 1
    print('==========task OK!==========')
if __name__ == "__main__":
    cpfile_rand('img', 'outfile', 10) # 操作目錄,輸出目錄,輸出數量

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM