|
@@ -14,23 +14,17 @@
|
|
|
|
|
|
import os
|
|
import os
|
|
import tarfile
|
|
import tarfile
|
|
|
|
+import gzip
|
|
|
|
|
|
def compress_file_tar(file_path, output_filename):
|
|
def compress_file_tar(file_path, output_filename):
|
|
# 确保输出文件名以 .tar.gz 结尾
|
|
# 确保输出文件名以 .tar.gz 结尾
|
|
if not output_filename.endswith('.tar.gz'):
|
|
if not output_filename.endswith('.tar.gz'):
|
|
output_filename += '.tar.gz'
|
|
output_filename += '.tar.gz'
|
|
- # 创建一个 tarfile 对象,使用 'w:gz' 模式表示写入 gzip 压缩的 tar 包
|
|
|
|
- with tarfile.open(output_filename, "w:gz", format=tarfile.GNU_FORMAT) as tar:
|
|
|
|
- # 将文件添加到 tar 包中,arcname 指定在 tar 包中的相对路径
|
|
|
|
- #tar.add(file_path, arcname=os.path.basename(file_path))
|
|
|
|
- file_name = os.path.basename(file_path)
|
|
|
|
- # 打开文件
|
|
|
|
- with open(file_path, 'rb') as file_to_add:
|
|
|
|
- # 创建一个TarInfo对象,设置其名称为文件名
|
|
|
|
- tar_info = tarfile.TarInfo(name=file_name)
|
|
|
|
- # 从文件中读取内容并写入TarInfo对象
|
|
|
|
- tar_info.size = os.path.getsize(file_path)
|
|
|
|
- tar.addfile(tar_info, fileobj=file_to_add)
|
|
|
|
|
|
+ with gzip.open(output_filename, 'wb') as gzip_file:
|
|
|
|
+ # 打开原始文件用于读取
|
|
|
|
+ with open(file_path, 'rb') as file_to_compress:
|
|
|
|
+ # 直接将文件数据写入gzip压缩流中
|
|
|
|
+ gzip_file.writelines(file_to_compress)
|
|
|
|
|
|
def compress_tar(folder_path, output_filename):
|
|
def compress_tar(folder_path, output_filename):
|
|
# 确保输出文件名以 .tar.gz 结尾
|
|
# 确保输出文件名以 .tar.gz 结尾
|