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 exists?
This error has the following causes and solutions: This error occurs at run time when the new file name, for example, one specified in a Name statement, is identical to a file name that already exists. Specify a new file name in the Name statement or delete the old file before specifying it in a Name statement.
basename(src_filename)); shutil. move(src_filename, dst_filename) --> then you don't get an exception raised. You don't need to specify the full path. If the filename is included in the destination path (relative or absolute) shutil will overwrite.
To overwrite a file, to write new content into a file, we have to open our file in “w” mode, which is the write mode. It will delete the existing content from a file first; then, we can write new content and save it. We have a new file with the name “myFile. txt”.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With