shutil 所有函数使用详解
时间: 2024-06-10 20:10:33 浏览: 6
`shutil` 模块是 Python 标准库中的一个文件和目录操作工具,它提供了一些常用的文件和目录操作函数,如拷贝、移动、删除、压缩等。
以下是 `shutil` 模块中常用函数的详细介绍:
## 1. copy(src, dst)
将文件从 `src` 复制到 `dst`,其中 `src` 和 `dst` 都可以是文件名或目录名。
```python
import shutil
shutil.copy('src.txt', 'dst.txt')
```
## 2. copy2(src, dst)
将文件从 `src` 复制到 `dst`,保留文件的元数据(如权限、时间戳等)。
```python
import shutil
shutil.copy2('src.txt', 'dst.txt')
```
## 3. copyfile(src, dst)
将文件从 `src` 复制到 `dst`,不保留文件的元数据。
```python
import shutil
shutil.copyfile('src.txt', 'dst.txt')
```
## 4. copytree(src, dst)
将目录从 `src` 复制到 `dst`,包括目录下的所有子目录和文件。
```python
import shutil
shutil.copytree('src_dir', 'dst_dir')
```
## 5. rmtree(path)
递归地删除一个目录及其所有子目录和文件。
```python
import shutil
shutil.rmtree('dir_to_delete')
```
## 6. move(src, dst)
将文件或目录从 `src` 移动到 `dst`。
```python
import shutil
shutil.move('src.txt', 'dst.txt')
```
## 7. make_archive(base_name, format, root_dir)
创建一个压缩包,其中 `base_name` 是文件名(不包括扩展名),`format` 是压缩格式(如 zip、tar 等),`root_dir` 是要压缩的根目录。
```python
import shutil
shutil.make_archive('archive', 'zip', 'dir_to_compress')
```
## 8. unpack_archive(filename, extract_dir)
解压缩一个压缩包,其中 `filename` 是压缩包文件名,`extract_dir` 是解压目录。
```python
import shutil
shutil.unpack_archive('archive.zip', 'extract_dir')
```
以上是 `shutil` 模块中常用函数的详细介绍。