tar_files.py 2.3 KB
Newer Older
F
FondMemoryVVV 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (c) 2020-2021 Huawei Device Co., Ltd.
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 argparse
import tarfile
import shutil

F
FondMemoryVVV 已提交
23 24 25 26 27 28 29 30 31 32 33 34
copy_file_counts = 0


def copy_files(sourcedir, targetDir):
    global copy_file_counts
    for f in os.listdir(sourcedir):
        source_f = os.path.join(sourcedir, f)
        target_f = os.path.join(targetDir, f)
        if not os.path.isfile(source_f):
            if os.path.isdir(source_f):
                copy_files(source_f, target_f)
        elif os.path.isfile(source_f):
F
FondMemoryVVV 已提交
35
            if os.path.exists(targetDir):
F
FondMemoryVVV 已提交
36 37 38
                copy_file_counts += 1
                with open(target_f, "wb") as fp: 
                    fp.write(open(source_f, "rb").read())
F
FondMemoryVVV 已提交
39 40
            elif not os.path.exists(targetDir):
                os.makedirs(targetDir)
F
FondMemoryVVV 已提交
41 42 43 44
                copy_file_counts += 1
                with open(target_f, "wb") as fp: 
                    fp.write(open(source_f, "rb").read())

F
FondMemoryVVV 已提交
45 46

def make_targz_one_by_one(output_filename, source_dir):
F
FondMemoryVVV 已提交
47 48 49 50 51
    tar = tarfile.open(output_filename, "w")
    for root, dirs, files in os.walk(source_dir):
        for file in files:
            pathfile = os.path.join(root, file)
            tar.add(pathfile)
F
FondMemoryVVV 已提交
52 53
    tar.close()

F
FondMemoryVVV 已提交
54

F
FondMemoryVVV 已提交
55 56 57 58 59 60 61 62 63 64
if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='manual to this script')
    parser.add_argument("--input_path", type=str, default="0")
    parser.add_argument("--output_path", type=str, default="0")
    parser.add_argument("--temp_path", type=str, default="0")
    args = parser.parse_args()
    print(args.input_path)
    print(args.output_path)
    print(args.temp_path)

F
FondMemoryVVV 已提交
65
    copy_files(args.input_path, args.temp_path)
F
FondMemoryVVV 已提交
66 67
    make_targz_one_by_one(args.output_path, args.temp_path)

F
FondMemoryVVV 已提交
68
    shutil.rmtree(args.temp_path) # delete middle files