Яндекс.Метрика

вторник, 6 октября 2015 г.

Tarfile with Python in memory using StringIO

#!/usr/bin/env python
# encoding=utf-8

from StringIO import StringIO
import tarfile


tario = StringIO()

# Files content:
data1 = "hello"
data2 = "world"

# Create tarfile object with file in memory tario:
tar_file = tarfile.open(fileobj=tario, mode='w:gz')

# Add first file and its info in the tar archive
# and save the unicode name of the file
info1 = tarfile.TarInfo(u"Привет.txt")
info1.size = len(data1)
tar_file.addfile(info1, fileobj=StringIO(data1))

# Add second file and its info in the tar archive
# and encode its name in utf-8:
info2 = tarfile.TarInfo(u"Мир.txt".encode('utf-8'))
info2.size = len(data2)
tar_file.addfile(info2, fileobj=StringIO(data2))

# Close tarfile object
tar_file.close()

# Write tarfile content to the file on disk
with open('realtar.tar.gz', 'w') as f:
    f.write(tario.getvalue())

Комментариев нет:

Отправить комментарий