【Python3】复制、移动、删除文件及文件夹

对于文件和文件夹,我们最常做的操作分为三种:复制、移动、删除。

这三种操作可以通过shutil和os模块中的函数实现,下面通过对hello.txt的操作为例进行说明:

*复制:shutil.copy(source, destination)   #复制文件

             shutil.copytree(source, destination)   #复制文件夹

*移动:shutil.move(source, destination);

*删除:os.unlink()         #删除文件

            os.rmdir()          #删除文件夹,文件夹必须为空

            shutil.rmtree()   #删除文件夹,包含文件夹及文件夹下的所有文件

hello.txt位于"C:\myweb\chapter01"目录下:

>>> import shutil, os
>>> os.chdir(r'C:\myweb\chapter01')
>>> os.listdir()
['Calculator.php', 'ex1_1.php', 'hello.txt', 'welcome.php', '_notes']

 

一、复制

1. 复制文件

#复制hello.txt到"C:\myweb\chapter02"目录下
>>> shutil.copy('hello.txt', r'C:\myweb\chapter02')
		
'C:\\myweb\\chapter02\\hello.txt'

#复制hello.txt到"C:\myweb\chapter02"目录并修改名称为hello_01.txt
>>> shutil.copy('hello.txt', r'C:\myweb\chapter02\hello_01.txt')
		    
'C:\\myweb\\chapter02\\hello_01.txt'

2. 复制文件夹

#复制"C:\myweb\chapter01"到"C:\myweb\chapter02"目录下
>>> shutil.copytree(r'C:\myweb\chapter01', r'C:\myweb\chapter02\chapter01')
		    
'C:\\myweb\\chapter02\\chapter01'

#复制"C:\myweb\chapter01"到"C:\myweb\chapter02"目录下并修改名称为chapter01_bak
>>> shutil.copytree(r'C:\myweb\chapter01', r'C:\myweb\chapter02\chapter01_bak')
		    
'C:\\myweb\\chapter02\\chapter01_bak'

二、移动

1. 移动文件

#移动hello.txt到"C:\myweb\chapter02"目录下,并修改名称为hello_02.txt
>>> shutil.move('hello.txt', r'C:\myweb\chapter02\hello_02.txt')
		
'C:\\myweb\\chapter02\\hello_02.txt'

2. 移动文件夹

#创建test文件夹并将其移动至chapter02文件夹下
>>> os.mkdir(r'C:\myweb\chapter01\test')
>>> os.path.isdir(r'C:\myweb\chapter01\test')
		
True
>>> shutil.move(r'C:\myweb\chapter01\test', r'C:\myweb\chapter02\test')
		
'C:\\myweb\\chapter02\\test'

三、 删除

1. 删除文件

#删除文件hello_02.txt
>>> os.chdir(r'C:\myweb\chapter02')
		
>>> os.listdir(os.getcwd())
		
['CalculatorII.php', 'chapter01', 'chapter01_bak', 'circleCal.php', 'hello.txt', 'hello_01.txt', 'hello_02.txt', 'Square.php', 'test']
>>> os.unlink('hello_02.txt')
		
>>> os.listdir(os.getcwd())
		
['CalculatorII.php', 'chapter01', 'chapter01_bak', 'circleCal.php', 'hello.txt', 'hello_01.txt', 'Square.php', 'test']

2. 删除空文件夹

#删除空文件夹test
>>> os.rmdir(r'./test')
		
>>> os.listdir(os.getcwd())
		
['CalculatorII.php', 'chapter01', 'chapter01_bak', 'circleCal.php', 'hello.txt', 'hello_01.txt', 'Square.php']

3. 删除非空文件夹

#删除非空文件夹chapter01
>>> shutil.rmtree(r'C:\myweb\chapter01')

 

  • 19
    点赞
  • 54
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值