python - shutil.move() 比 os.remove() + os.rename() 慢

标签 python python-3.x

所以,我注意到当我想移动文件 '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

最佳答案

如果 srcdst 在不同的文件系统上,则不能保证 os.rename(src, dst) 工作。如果 dst 存在,它在 Windows 上不起作用。

正如the docs

关于python - shutil.move() 比 os.remove() + os.rename() 慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23232518/

相关文章:

python - 如何将粗俗分数转换为 float ?

python - BeautifulSoup 找不到 xml 标签,我该如何解决?

python - 是否有访问列表的 "get or default"方式?

python - 我在 `pygame` 中的圆圈超出了边界然后又回来了(穿过边界)

c# - 哪些 Python 特性会激发 C# 开发人员的兴趣?

python - 如何优雅地迭代列表或字典

python - 如何解释反向传播的计算图?

python-3.x - 一旦获得多变量多项式回归的一组系数,如何解释模型?

python - 排除区间的端点

python - 如何检查是否有互联网连接