[英]shutil.move() slower than os.remove() + os.rename()
因此,我注意到,當我想移動文件'a'並覆蓋目標位置'b'時,os.remove('b')然后os.rename('a','b')的速度比shutil快得多.move('a','b')。
我讀過說 :
如果目標位於當前文件系統上,則使用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
如果src
和dst
在不同的文件系統上os.rename(src, dst)
則不能保證os.rename(src, dst)
可以工作。 如果存在dst
,則無法在Windows上使用。
正如文檔所說
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.