对于文件和文件夹,我们最常做的操作分为三种:复制、移动、删除。
		这三种操作可以通过shutil和os模块中的函数实现,下面通过对hello.txt的操作为例进行说明:
| 12
 3
 4
 5
 6
 7
 8
 
 | shutil.copy(source, destination)   shutil.copytree(source, destination)
 
 shutil.move(source, destination)
 
 os.unlink()
 os.rmdir()
 shutil.rmtree()
 
 | 
复制
复制文件
| 12
 3
 4
 5
 6
 7
 8
 9
 
 | >>> shutil.copy('hello.txt', r'C:\myweb\chapter02')
 
 'C:\\myweb\\chapter02\\hello.txt'
 
 
 >>> shutil.copy('hello.txt', r'C:\myweb\chapter02\hello_01.txt')
 
 'C:\\myweb\\chapter02\\hello_01.txt'
 
 | 
复制文件夹
| 12
 3
 4
 5
 6
 7
 8
 9
 
 | >>> shutil.copytree(r'C:\myweb\chapter01', r'C:\myweb\chapter02\chapter01')
 
 'C:\\myweb\\chapter02\\chapter01'
 
 
 >>> shutil.copytree(r'C:\myweb\chapter01', r'C:\myweb\chapter02\chapter01_bak')
 
 'C:\\myweb\\chapter02\\chapter01_bak'
 
 | 
移动
移动文件
| 12
 3
 4
 
 | >>> shutil.move('hello.txt', r'C:\myweb\chapter02\hello_02.txt')
 
 'C:\\myweb\\chapter02\\hello_02.txt'
 
 | 
移动文件夹
| 12
 3
 4
 5
 6
 7
 8
 
 | >>> 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'
 
 | 
删除
删除文件
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 
 | >>> 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']
 
 | 
删除空文件夹
| 12
 3
 4
 5
 6
 
 | >>> os.rmdir(r'./test')
 
 >>> os.listdir(os.getcwd())
 
 ['CalculatorII.php', 'chapter01', 'chapter01_bak', 'circleCal.php', 'hello.txt', 'hello_01.txt', 'Square.php']
 
 | 
删除非空文件夹
| 12
 
 | >>> shutil.rmtree(r'C:\myweb\chapter01')
 
 |