Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileExistsError: [WinError 183] Cannot create a file when that file already exists:

Tags:

python-2.7

i when run this test program create the below error.

import shutil    
src=r"G:\aaa"     
dst=r"F:\zzz"    
shutil.copytree(src,dst, symlinks=False, ignore=None)      

FileExistsError: [WinError 183] Cannot create a file when that file already exists:

but the the folder of F:\zzz is empty!!!

like image 453
ali alavi Avatar asked Sep 05 '17 19:09

ali alavi


People also ask

Was Error 183 Cannot create a file when that file already exists?

183: Cannot create a new file when that file already exists. This is a generic Windows Services error that is returned when a service cannot be successfully started. There are a variety of possible situations that can prevent the Laserfiche Server service from successfully starting.


2 Answers

shutil.copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False, dirs_exist_ok=False)

dirs_exist_ok dictates whether to raise an exception in case dst or any missing parent directory already exists.

Python 3.8 now have support of dirs_exist_ok parameter. This won't give that error anymore and overwrite the destination folder in case it already exists.

Hence you need to use:

shutil.copytree(src, dst, dirs_exist_ok=True)
like image 110
Shivansh Mathur Avatar answered Oct 11 '22 03:10

Shivansh Mathur


"Cannot create a file when that file already exists" is a generic Windows message which is confusing because it's the same for directories or regular files. (Windows isn't known for very helpful error messages, you have to make do with that)

from the online help of shutil.copytree:

>>> help(shutil.copytree)

Help on function copytree in module shutil:

copytree(src, dst, symlinks=False, ignore=None, copy_function=, ignore_dangling_symlinks=False)

Recursively copy a directory tree.

The destination directory must not already exist.

So first time it probably works, but other times you need to perform

shutil.rmtree(dst)

to remove the destination directory prior to copying the tree (note that Windows is annoying with permissions and that files with read-only attribute can choke shutil.rmtree, which I personally copied the code into a custom version (you're encouraged to do so in the online help) to add a os.chmod(path,0o777) prior to deleting regular files.

like image 27
Jean-François Fabre Avatar answered Oct 11 '22 03:10

Jean-François Fabre