所以,我注意到当我想移动文件 'a' 并覆盖目标 'b' os.remove('b') 然后 os.rename('a','b') 很多比 shutil.move('a','b') 更快。
我读过 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.
但为什么它不使用 os.remove() 呢?
示例(第一次使用timeit,如有错误请见谅):
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))
打印:
shutil.move(): 0.81
os.rename(): 0.052
最佳答案
如果 src
和 dst
在不同的文件系统上,则不能保证 os.rename(src, dst)
工作。如果 dst
存在,它在 Windows 上不起作用。
正如the docs说
关于python - shutil.move() 比 os.remove() + os.rename() 慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23232518/