简体   繁体   中英

shutil.move() slower than os.remove() + os.rename()

So, I noticed that when I want to move a file 'a' and overwrite the destination 'b' os.remove('b') and then os.rename('a','b') is a lot faster than shutil.move('a','b').

I've read that :

If the destination is on the current filesystem, then os.rename() is used. Otherwise, src is copied (using shutil.copy2()) to dst and then removed. In case of symlinks, a new symlink pointing to the target of src will be created in or as dst and src will be removed.

but why doesn't it use os.remove() also?

Example (1st time using timeit, sorry if I have any mistakes):

import os,timeit
os.chdir('c:\python')
def myMove(a,b):
    os.remove(b)
    os.rename(a,b)

with open('src1', 'wb') as fout:
    fout.write(os.urandom(350000000))
with open('src2', 'wb') as fout:
    fout.write(os.urandom(350000000))
with open('dest1', 'wb') as fout:
    fout.write(os.urandom(350000000))
with open('dest2', 'wb') as fout:
    fout.write(os.urandom(350000000))

print('shutil.move(): %.3f' %timeit.timeit('shutil.move(os.path.join("c:\python","src1"),os.path.join("c:\python","dest1"))','import shutil,os.path', number = 1))
print('os.rename(): %.3f' %timeit.timeit('myMove("src2","dest2")','from __main__ import myMove', number = 1))

prints:

shutil.move(): 0.81

os.rename(): 0.052

There is no guarantee that os.rename(src, dst) works if src and dst are on different filesystems. And it does not work on Windows if dst exists.

Just as the docs say

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM