zoukankan      html  css  js  c++  java
  • 【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
  • 相关阅读:
    记录log中的16进制和ASCII码字符输出
    有效的沟通技巧
    时间的真谛
    目标设定与时间管理
    第四代时间管理
    什么是高效沟通
    error LNK1104: cannot open file 错误解决方案
    js压缩工具1.0界面绘制
    时间管理的定义与目的
    JArgs命令行选项解析>Java套件
  • 原文地址:https://www.cnblogs.com/dplearning/p/6224941.html
Copyright © 2011-2022 走看看