shutil 模块中 shutil.copy()、shutil.rmtree()、shutil.move()等基本函数用法介绍!

关注公众号:【小张Python】,为你准备了 50+ 本Python 精品电子书籍 与 50G + 优质视频学习资料,后台回复关键字:1024 即可获取;如果对博文内容有什么疑问,后台添加作者【个人微信】,可与作者直接进行交流

shutil.copyfile(src,dst)
  • src(str),文件路径;
  • dst(str),文件路径;

将文件 src 复制到 文件 dst 中,复制成功后返回 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) 相同,用于文件复制;唯一区别是 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 中全部文件递归复制到 dst ,dst 若不存在时系统自动创建~

>>> 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),文件夹目录;

递归删除整个文件夹下所有文件,包括此文件夹;

>>> 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),文件夹目录;

将文件或整个文件目录 src 移动到 dst ,移动成功后返回目标文件路径;若 dst 不存在时自动创建

>>> 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),文件路径或文件夹路径;

以给定元组形式返回有关给定路径下磁盘使用情况的统计信息,元组中包含三个元素分别表示总容量、已使用容量、剩余容量,是以字节为单位

>>> 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)
  • 20
    点赞
  • 168
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员大飞1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值