常用的压缩算法代码
时间: 2023-07-09 09:10:42 浏览: 47
以下是常用的压缩算法的代码示例:
1. ZIP:
使用Python中的zipfile模块进行ZIP压缩:
```python
import zipfile
# 创建一个压缩文件
with zipfile.ZipFile('example.zip', 'w') as zip:
# 将文件添加到压缩文件中
zip.write('file1.txt')
zip.write('file2.txt')
```
2. RAR:
使用Python中的rarfile模块进行RAR压缩:
```python
import rarfile
# 创建一个压缩文件
with rarfile.RarFile('example.rar', 'w') as rar:
# 将文件添加到压缩文件中
rar.write('file1.txt')
rar.write('file2.txt')
```
3. GZIP:
使用Python中的gzip模块进行GZIP压缩:
```python
import gzip
# 打开要进行压缩的文件
with open('example.txt', 'rb') as f_in:
# 创建一个压缩文件
with gzip.open('example.txt.gz', 'wb') as f_out:
# 将数据压缩并写入压缩文件中
f_out.write(f_in.read())
```
4. LZ77/LZ78:
使用Python中的lzma模块进行LZ77/LZ78压缩:
```python
import lzma
# 打开要进行压缩的文件
with open('example.txt', 'rb') as f_in:
# 创建一个压缩文件
with lzma.open('example.txt.lzma', 'w') as f_out:
# 将数据压缩并写入压缩文件中
f_out.write(f_in.read())
```
5. DEFLATE:
使用Python中的zlib模块进行DEFLATE压缩:
```python
import zlib
# 打开要进行压缩的文件
with open('example.txt', 'rb') as f_in:
# 创建一个压缩文件
with open('example.txt.deflate', 'wb') as f_out:
# 将数据压缩并写入压缩文件中
f_out.write(zlib.compress(f_in.read()))
```