python write string directly to tarfile

后端 未结 7 1277
-上瘾入骨i
-上瘾入骨i 2020-12-08 13:28

Is there a way to write a string directly to a tarfile? From http://docs.python.org/library/tarfile.html it looks like only files already written to the file system can be a

7条回答
  •  执笔经年
    2020-12-08 13:54

    As Stefano pointed out, you can use TarFile.addfile and StringIO.

    import tarfile, StringIO
    
    data = 'hello, world!'
    
    tarinfo = tarfile.TarInfo('test.txt')
    tarinfo.size = len(data)
    
    tar = tarfile.open('test.tar', 'a')
    tar.addfile(tarinfo, StringIO.StringIO(data))
    tar.close()
    

    You'll probably want to fill other fields of tarinfo (e.g. mtime, uname etc.) as well.

提交回复
热议问题