Move and replace if same file name already exists?

后端 未结 2 1601
北恋
北恋 2020-12-02 14:16

Here is below code which will move and replace individual file:

import shutil
import os
src = \'scrFolder\'
dst = \'./dstFolder/\'
filelist = []

files = os.         


        
相关标签:
2条回答
  • 2020-12-02 14:54

    I got it to overwrite by providing a full path for both source and target in the move command... remember to add double slash for Windows paths.

    # this is to change directories (type your own)
    os.chdir("C:\REPORTS\DAILY_REPORTS")
    
    # current dir  (to verify)
    cwd = os.getcwd() 
    src = cwd
    dst = cwd + '\\XLS_BACKUP\\'
    
    shutil.move(os.path.join(src, file), os.path.join(dst, file))
    
    # nice and short.
    
    0 讨论(0)
  • 2020-12-02 14:55

    If you specify the full path to the destination (not just the directory) then shutil.move will overwrite any existing file:

    shutil.move(os.path.join(src, filename), os.path.join(dst, filename))
    
    0 讨论(0)
提交回复
热议问题