使用Python标准库tarfile把当前文件夹中所有.py文件压缩为gzip格式的压缩文件,然后再压缩到指定文件夹中
时间: 2023-08-06 11:02:27 浏览: 48
好的,下面是 Python 代码实现:
```python
import os
import tarfile
import gzip
# 定义要压缩的文件夹路径
source_dir = os.getcwd()
# 定义压缩文件名和压缩格式
filename = 'python_files.tar.gz'
# 定义要保存的压缩文件夹路径
target_dir = '/path/to/target/directory/'
# 创建 tar 文件对象
tar = tarfile.open(target_dir + filename, 'w:gz')
# 遍历当前文件夹中所有 .py 文件,添加到 tar 文件对象中
for file in os.listdir(source_dir):
if file.endswith('.py'):
tar.add(file)
# 关闭 tar 文件对象
tar.close()
# 打开新创建的 tar 文件对象,以 gzip 格式压缩
with open(target_dir + filename, 'rb') as f_in:
with gzip.open(target_dir + filename + '.gz', 'wb') as f_out:
f_out.writelines(f_in)
# 删除原始的 tar 文件
os.remove(target_dir + filename)
```
这段代码首先定义了要压缩的文件夹路径、压缩文件名和压缩格式、要保存的压缩文件夹路径。然后创建一个 tar 文件对象,遍历当前文件夹中所有 .py 文件,将其添加到 tar 文件对象中,并关闭该文件对象。接着打开新创建的 tar 文件对象,以 gzip 格式压缩,最后删除原始的 tar 文件。