Move and replace if same file name already existed in python

喜欢而已 提交于 2019-12-03 18:28:23

问题


Here is below code which will move and replace individual file

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

files = os.listdir( src )
for filename in files:
 filelist.append(filename)
 fullpath = src + '/' + filename
 shutil.move(fullpath, dst)

If i execute same command and moving file which already existed in dst folder i am getting shutil.Error: Destination path './dstFolder/file.txt' already exists how to do move and replace if same file name already existed


回答1:


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))



回答2:


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.


来源:https://stackoverflow.com/questions/31813504/move-and-replace-if-same-file-name-already-existed-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!