1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
- #
- # Licensed under the Apache License, Version 2.0 (the "License");
- # you may not use this file except in compliance with the License.
- # You may obtain a copy of the License at
- #
- # http://www.apache.org/licenses/LICENSE-2.0
- #
- # Unless required by applicable law or agreed to in writing, software
- # distributed under the License is distributed on an "AS IS" BASIS,
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- # See the License for the specific language governing permissions and
- # limitations under the License.
- import os
- import tarfile
- def compress_file_tar(file_path, output_filename):
- # 确保输出文件名以 .tar.gz 结尾
- if not output_filename.endswith('.tar.gz'):
- output_filename += '.tar.gz'
- # 创建一个 tarfile 对象,使用 'w:gz' 模式表示写入 gzip 压缩的 tar 包
- with tarfile.open(output_filename, "w:gz") as tar:
- # 将文件添加到 tar 包中,arcname 指定在 tar 包中的相对路径
- tar.add(file_path, arcname=os.path.relpath(file_path))
- def compress_tar(folder_path, output_filename):
- # 确保输出文件名以 .tar.gz 结尾
- if not output_filename.endswith('.tar.gz'):
- output_filename += '.tar.gz'
- # 创建一个 tarfile 对象,使用 'w:gz' 模式表示写入 gzip 压缩的 tar 包
- with tarfile.open(output_filename, "w:gz") as tar:
- # os.walk() 遍历目录
- for root, dirs, files in os.walk(folder_path):
- for file in files:
- # 构建完整的文件路径
- file_path = os.path.join(root, file)
- # 将文件添加到 tar 包中,arcname 指定在 tar 包中的相对路径
- tar.add(file_path, arcname=os.path.relpath(file_path, start=folder_path))
- def uncompress_tar(compressed_filename, output_folder):
- """
- 解压 .tar.gz 文件到指定的输出文件夹。
- Args:
- compressed_filename (str): 要解压的 .tar.gz 文件的路径。
- output_folder (str): 解压文件的目标文件夹路径。
- """
- # 确保输出文件夹存在
- if not os.path.exists(output_folder):
- os.makedirs(output_folder)
- # 打开 .tar.gz 文件进行解压缩
- with tarfile.open(compressed_filename, "r:gz") as tar:
- # 解压 tar 包到指定的输出文件夹
- tar.extractall(path=output_folder)
- if __name__ == "__main__":
- folder_path="/Users/dingyunpeng/tardemo"
- output_filename="/Users/dingyunpeng/tardemo.tar.gz"
- compressed_filename=output_filename
- output_folder=folder_path + "2"
- compress_tar(folder_path, output_filename)
- uncompress_tar(output_filename, output_folder)
|