shutil 模塊中 shutil.copy()、shutil.rmtree()、shutil.move()等基本函數(shù)用法介紹!

shutil.copyfile(src,dst)

  • src(str),文件路徑;
  • dst(str),文件路徑;

將文件 src 復(fù)制到 文件 dst 中,復(fù)制成功后返回 dst 完整路徑;src,dst 需是文件路徑而非文件目錄

>>> shutil.copyfile(os.getcwd()+'/Map123.gif',os.getcwd()+'/ceshi.gif')
'D:\\Data\\map_data/ceshi.gif'
>>> os.listdir()
['ceshi.gif', 'map-location.xlsx', 'Map123.gif', 'recu_dir']

shutil.copy(src,dst)

  • src(str),文件路徑;
  • dst(str),文件路徑或文件目錄;

作用與 shutil.copy(src,dst) 相同,用于文件復(fù)制;唯一區(qū)別是 shutil.copy() 中 dst 可為文件路徑或文件目錄;

>>> shutil.copy(os.getcwd() +'/ceshi.gif',os.getcwd() +'/recu_dir')
'D:\\Data\\map_data/recu_dir\\ceshi.gif'
>>>

shutil.copytree(src,dst)

  • scr(str),文件夾目錄;
  • dst(str),文件夾目錄;

將文件夾 src 中全部文件遞歸復(fù)制到 dst ,dst 若不存在時(shí)系統(tǒng)自動(dòng)創(chuàng)建~

>>> os.listdir()
['ceshi.gif', 'dir1_fir', 'map-location.xlsx', 'Map123.gif']
>>> shutil.copytree(os.getcwd() +'/dir1_fir',os.getcwd() +'/dir_file')
'D:\\Data\\map_data/dir_file'
>>> os.lisdir()
>>> os.listdir()
['ceshi.gif', 'dir1_fir', 'dir_file', 'map-location.xlsx', 'Map123.gif']
>>> os.listdir(os.getcwd() +'/dir_file')
['dir_second']

shutil.rmtree(path)

  • path(str),文件夾目錄;

遞歸刪除整個(gè)文件夾下所有文件,包括此文件夾;

>>> os.listdir()
['ceshi.gif', 'dir_first', 'map-location.xlsx', 'Map123.gif', 'recu_dir']
>>> os.listdir(os.getcwd() +'/recu_dir')
['ceshi.gif', 'file_dir', 'Map123.gif']
>>> shutil.rmtree(os.getcwd() +'/recu_dir')
>>> os.listdir()
['ceshi.gif', 'dir_first', 'map-location.xlsx', 'Map123.gif']
>>>

shutil.move(src,dst)

  • src(str),文件路徑或文件夾目錄;
  • dst(str),文件夾目錄;

將文件或整個(gè)文件目錄 src 移動(dòng)到 dst ,移動(dòng)成功后返回目標(biāo)文件路徑;若 dst 不存在時(shí)自動(dòng)創(chuàng)建

>>> os.listdir()
['ceshi.gif', 'dir_first', 'map-location.xlsx', 'Map123.gif']
>>> shutil.move(os.getcwd() +'/dir_first',os.getcwd() +'/dir1_fir')
'D:\\Data\\map_data/dir1_fir'
>>> os.listdir()
['ceshi.gif', 'dir1_fir', 'map-location.xlsx', 'Map123.gif']

shutil.disk_usage(path)

  • path(str),文件路徑或文件夾路徑;

以給定元組形式返回有關(guān)給定路徑下磁盤使用情況的統(tǒng)計(jì)信息,元組中包含三個(gè)元素分別表示總?cè)萘?、已使用容量、剩余容量,是以字?jié)為單位

>>> shutil.disk_usage(os.getcwd())
usage(total=268435456000, used=187079077888, free=81356378112)
>>> os.getcwd()
'D:\\Data\\map_data'
>>> shutil.disk_usage('D:/')
usage(total=268435456000, used=187079077888, free=81356378112)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容