【发布时间】:2014-06-07 14:10:50
【问题描述】:
所以,我注意到当我想移动文件 'a' 并覆盖目标 'b' os.remove('b') 然后 os.rename('a','b') 很多比 shutil.move('a','b') 更快。
我读过that:
如果目标位于当前文件系统上,则使用 os.rename()。否则,src 被复制(使用 shutil.copy2())到 dst,然后被删除。如果是符号链接,将在 dst 中或作为 dst 中创建指向 src 目标的新符号链接,并将删除 src。
但为什么不使用 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
【问题讨论】:
标签: python python-3.x