파이썬

[파이썬] 디렉터리마다 파일 n개씩만 다른 폴더로 복사하기

Heeyeon Choi 2023. 4. 5. 14:31
728x90
728x90
import os
import shutil
import natsort as natsort

NAME_PATH = os.path.join(os.getcwd() + '/training/')
IMG_PATH = os.path.join(os.getcwd() + '/target/')
PATH = os.getcwd()

count = 0
one = os.listdir(IMG_PATH)
one = natsort.natsorted(one)
for i in one:
    two = natsort.natsorted(os.listdir(os.path.join(os.getcwd() + '/target/'+i+"/")))
    for j in two:
        three = natsort.natsorted(os.listdir(os.path.join(os.getcwd() + '/target/' + i + "/"+j+"/")))
        for k in three:
            shutil.copy(os.getcwd() + '/target/' + i + "/"+j+"/"+k, NAME_PATH+k)
            count = count + 1
            if count == 3:
                count = 0
                break
  • 폴더 안에 폴더가 존재
  • 이중 for문으로 검사
  • shutil.copy(os.getcwd() + '/target/' + i + "/"+j+"/"+k, NAME_PATH+k) 
    • shutil.copy를 사용하여 파일 복사

 

728x90