• 【python】tarfile的路径问题


    假设有路径/home/somebody/test1/test2/test3/

    该路径下有3个文件,a.txt, b.txt, c.txt

    在目录/home/somebody下有如下代码,希望打包a.txt, b.txt, c.txt三个文件

    #coding=utf8
    import json
    import gzip
    import msgpackimport tarfile
    import os
    
    def test_tar(fname_out, dir_in):
        tar = tarfile.open(fname_out, 'w:gz')
        for root, dir, files in os.walk(dir_in):
            for file in files:
                fullpath = os.joinpath(root, file)
                tar.add(fullpath)
        tar.close()
        os.chdir(cur_path)
    
    if __name__ == "__main__":
        test_tar("test_tar.gz", "test1/test2/test3")

     解压test_tar.gz结果

    test1/test2/test3/a.txt
    test1/test2/test3/b.txt
    test1/test2/test3/c.txt

    问题出现了,解压后保留了原有的路径!!可这不是我想要的啊,我只想要三个文件啊!

    解决办法:

    经测试,压缩文件的路径跟tarfile.add()中的路径完全一致,所以需要在add时把当当前目录转换到/home/somebody/test1/test2/test3/,等打包后在把当前目录还原即可

    #coding=utf8
    import json
    import gzip
    import msgpack
    import urllib
    import urllib2
    import tarfile
    import os
    
    def test_tar(fname_out, dir_in):
        cur_path = os.getcwd()
        full_fname_out = os.path.join(cur_path, fname_out)
        full_path_in = os.path.join(cur_path, dir_in)
        os.chdir(full_path_in)
        tar = tarfile.open(full_fname_out, 'w:gz')
        for root, dir, files in os.walk(full_path_in):
            for file in files:
                fullpath = file
                tar.add(fullpath, recursive=False)
        tar.close()
        os.chdir(cur_path)
    
    if __name__ == "__main__":
        test_tar("test_tar.gz", "test1/test2/test3")

    代码如上所示,关键部分加粗显示了。这样解压结果中就没有复杂的目录结构了

    a.txt
    b.txt
    c.txt
  • 相关阅读:
    DRF
    DRF
    DRF
    DRF
    RESTful介绍
    DRF parser请求处理流程
    Vue项目的创建
    怎么清除file控件的文件路径
    java用spring实现文件下载
    JS判断元素是否在数组内 阿星小栈
  • 原文地址:https://www.cnblogs.com/dplearning/p/6224941.html
Copyright © 2020-2023  润新知