컴퓨터/Python

python 다른폴더에 파일 이동시킬 때 같은이름파일 있으면 같은파일지우고 새로운파일 이동

풍경소리^^ 2023. 12. 14. 11:08
import shutil
import os

home_path = os.path.expanduser('~')
source_path = os.path.join(home_path,"Downloads")
target_path = r'B:\python\hometax\data'
for filename in os.listdir(source_path):
    if filename.endswith(".pdf"):
        # print(os.path.join(source_path,filename))
        souce_file = os.path.join(source_path,filename)
        target_file = os.path.join(target_path,filename)
        if os.path.exists(target_file):
            os.remove(target_file)
            shutil.move(souce_file,target_file)