Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move and replace if same file name already exists?

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?

like image 983
user1891916 Avatar asked Aug 04 '15 15:08

user1891916


People also ask

How do you handle a file 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.

How do you replace a file with the same name in Python?

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.

How do you overwrite a file if it exists in Python?

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”.


1 Answers

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)) 
like image 117
ecatmur Avatar answered Sep 19 '22 22:09

ecatmur