Dir_util.copy_tree crashes after shutil.rmtree

I try to copy a folder to another after deleting it:

for i in range(0,3): try: dir_util.remove_tree("D:/test2") # shutil.rmtree("D:/test2") print "removed" except: pass dir_util.copy_tree("D:/test1", "D:/test2") print i 

D: / test1 contains one empty file called test_file. If I use dir_util.remove_tree, it works fine, but after shutil.rmtree it only works once, in the second iteration, it fails. Exit:

 removed 0 removed Traceback (most recent call last): File "test.py", line 53, in <module> dir_util.copy_tree("D:/test1", "D:/test2") File "C:\Python27\lib\distutils\dir_util.py", line 163, in copy_tree dry_run=dry_run) File "C:\Python27\lib\distutils\file_util.py", line 148, in copy_file _copy_file_contents(src, dst) File "C:\Python27\lib\distutils\file_util.py", line 44, in _copy_file_contents fdst = open(dst, 'wb') IOError: [Errno 2] No such file or directory: 'D:/test2\\test_file' 

I find it more convenient to use shutil.rmtree because it allows you to handle errors to delete read-only files. What is the difference between dir_util.remove_tree and shutil.rmtree? Why does copy_tree not work after rmtree a second time?

I am running Python 2.7.2 on Windows 7

+7
source share
5 answers

This seems to be a bug in distutils. If you copy a folder and then delete it and then copy it again, it will fail, because it caches all created directories. Bypass, you can clear _path_created before copying:

 distutils.dir_util._path_created = {} distutils.dir_util.copy_tree(src, dst) 
+16
source

Please read the distutil documentation, this module is for "Creating and Installing Python Modules" ( https://docs.python.org/2/library/distutils.html )

If you want to copy the directory tree from one place to another, you should take a look at shutil.copytree https://docs.python.org/2/library/shutil.html#shutil.copytree

+4
source

There seems to be a lack of consistency in the path separator. On Windows, you must use "\\" (must be escaped). * Nix systems use /.

You can use: os.path.join ("D: \\ test2", "test_file") to make it OS independent. Additional Information

+1
source

This is very similar to being bitten by variations of the path separators. Primary key:

 IOError: [Errno 2] No such file or directory: 'D:/test2\\test_file' 

Which combines the file name with the directory name using os.sep. I think you should use appropriate path separators if you can.

0
source

shutil.copytree works!

 if os.path.exists(dest): shutil.rmtree(dest) shutil.copytree(src, dest) 
0
source

Source: https://habr.com/ru/post/907766/


All Articles