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
source share