Files
ailearning/docs/da/144.md
2020-10-19 21:08:55 +08:00

173 lines
2.4 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# shutil 模块:高级文件操作
In [1]:
```py
import shutil
import os
```
`shutil``Python` 中的高级文件操作模块。
## 复制文件
In [2]:
```py
with open("test.file", "w") as f:
pass
print "test.file" in os.listdir(os.curdir)
```
```py
True
```
`shutil.copy(src, dst)` 将源文件复制到目标地址:
In [3]:
```py
shutil.copy("test.file", "test.copy.file")
print "test.file" in os.listdir(os.curdir)
print "test.copy.file" in os.listdir(os.curdir)
```
```py
True
True
```
如果目标地址中间的文件夹不存在则会报错:
In [4]:
```py
try:
shutil.copy("test.file", "my_test_dir/test.copy.file")
except IOError as msg:
print msg
```
```py
[Errno 2] No such file or directory: 'my_test_dir/test.copy.file'
```
另外的一个函数 `shutil.copyfile(src, dst)``shutil.copy` 使用方法一致,不过只是简单复制文件的内容,并不会复制文件本身的读写可执行权限,而 `shutil.copy` 则是完全复制。
## 复制文件夹
将文件转移到 `test_dir` 文件夹:
In [5]:
```py
os.renames("test.file", "test_dir/test.file")
os.renames("test.copy.file", "test_dir/test.copy.file")
```
使用 `shutil.copytree` 来复制文件夹:
In [6]:
```py
shutil.copytree("test_dir/", "test_dir_copy/")
"test_dir_copy" in os.listdir(os.curdir)
```
Out[6]:
```py
True
```
## 删除非空文件夹
`os.removedirs` 不能删除非空文件夹:
In [7]:
```py
try:
os.removedirs("test_dir_copy")
except Exception as msg:
print msg
```
```py
[Errno 39] Directory not empty: 'test_dir_copy'
```
使用 `shutil.rmtree` 来删除非空文件夹:
In [8]:
```py
shutil.rmtree("test_dir_copy")
```
## 移动文件夹
`shutil.move` 可以整体移动文件夹,与 `os.rename` 功能差不多。
## 产生压缩文件
查看支持的压缩文件格式:
In [9]:
```py
shutil.get_archive_formats()
```
Out[9]:
```py
[('bztar', "bzip2'ed tar-file"),
('gztar', "gzip'ed tar-file"),
('tar', 'uncompressed tar file'),
('zip', 'ZIP file')]
```
产生压缩文件:
`shutil.make_archive(basename, format, root_dir)`
In [10]:
```py
shutil.make_archive("test_archive", "zip", "test_dir/")
```
Out[10]:
```py
'/home/lijin/notes-python/11\. useful tools/test_archive.zip'
```
清理生成的文件和文件夹:
In [11]:
```py
os.remove("test_archive.zip")
shutil.rmtree("test_dir/")
```