복붙노트

[PYTHON] python 직접 tarfile에 문자열 쓰기

PYTHON

python 직접 tarfile에 문자열 쓰기

문자열을 tarfile에 직접 쓰는 방법이 있습니까? http://docs.python.org/library/tarfile.html에서 이미 파일 시스템에 작성된 파일 만 추가 할 수있는 것처럼 보입니다.

해결법

  1. ==============================

    1.TarInfo e TarFile.addfile을 사용하여 StringIO를 파일 객체로 전달함으로써 가능하다고 말할 수 있습니다.

    TarInfo e TarFile.addfile을 사용하여 StringIO를 파일 객체로 전달함으로써 가능하다고 말할 수 있습니다.

    매우 거칠지 만 작동합니다.

    import tarfile
    import StringIO
    
    tar = tarfile.TarFile("test.tar","w")
    
    string = StringIO.StringIO()
    string.write("hello")
    string.seek(0)
    info = tarfile.TarInfo(name="foo")
    info.size=len(string.buf)
    tar.addfile(tarinfo=info, fileobj=string)
    
    tar.close()
    
  2. ==============================

    2.Stefano가 지적했듯이, TarFile.addfile과 StringIO를 사용할 수 있습니다.

    Stefano가 지적했듯이, TarFile.addfile과 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()
    

    다른 tarinfo 필드 (예 : mtime, uname 등)도 채울 수 있습니다.

  3. ==============================

    3.장고에있는 방금 .tgz 아카이브에서 만든 방법을 찾는이 발견, 다른 사람이 내 코드를 유용하게 찾을 수 있습니다 :

    장고에있는 방금 .tgz 아카이브에서 만든 방법을 찾는이 발견, 다른 사람이 내 코드를 유용하게 찾을 수 있습니다 :

    import tarfile
    from io import BytesIO
    
    
    def serve_file(request):
        out = BytesIO()
        tar = tarfile.open(mode = "w:gz", fileobj = out)
        data = 'lala'.encode('utf-8')
        file = BytesIO(data)
        info = tarfile.TarInfo(name="1.txt")
        info.size = len(data)
        tar.addfile(tarinfo=info, fileobj=file)
        tar.close()
    
        response = HttpResponse(out.getvalue(), content_type='application/tgz')
        response['Content-Disposition'] = 'attachment; filename=myfile.tgz'
        return response
    
  4. ==============================

    4.기록만을 위해서: StringIO 개체에는 .len 속성이 있습니다. (0)을 찾고 len (foo.buf)을 수행 할 필요가 없습니다. len ()을 사용하기 위해 전체 문자열을 유지할 필요가 없으며, 또는 God이 금전적으로 회계를 수행하는 것을 금지합니다.

    기록만을 위해서: StringIO 개체에는 .len 속성이 있습니다. (0)을 찾고 len (foo.buf)을 수행 할 필요가 없습니다. len ()을 사용하기 위해 전체 문자열을 유지할 필요가 없으며, 또는 God이 금전적으로 회계를 수행하는 것을 금지합니다.

    (OP가 쓰여진 당시에는 아닐 수도 있습니다.)

  5. ==============================

    5.일반적인 add 메소드 대신에 TarInfo 객체와 addfile 메소드를 사용해야한다.

    일반적인 add 메소드 대신에 TarInfo 객체와 addfile 메소드를 사용해야한다.

    from StringIO import StringIO
    from tarfile import open, TarInfo
    
    s = "Hello World!"
    ti = TarInfo("test.txt")
    ti.size = len(s)
    
    tf = open("testtar.tar", "w")
    tf.addfile(ti, StringIO(s))
    
  6. ==============================

    6.제 경우에는 기존의 tar 파일을 읽고 내용에 데이터를 추가하고 새로운 파일에 쓰고 싶었습니다. 같은 것 :

    제 경우에는 기존의 tar 파일을 읽고 내용에 데이터를 추가하고 새로운 파일에 쓰고 싶었습니다. 같은 것 :

    for ti in tar_in:
        buf_in = tar.extractfile(ti)
        buf_out = io.BytesIO()
        size = buf_out.write(buf_in.read())
        size += buf_out.write(other data)
        buf_out.seek(0)
        ti.size = size
        tar_out.addfile(ti, fileobj=buf_out)
    

    디렉터리와 링크를 처리하려면 추가 코드가 필요합니다.

  7. ==============================

    7.Python 3의 솔루션은 io.BytesIO를 사용합니다. TarInfo.size는 문자열의 길이가 아닌 바이트의 길이로 설정하십시오.

    Python 3의 솔루션은 io.BytesIO를 사용합니다. TarInfo.size는 문자열의 길이가 아닌 바이트의 길이로 설정하십시오.

    단일 문자열이 주어진다면 가장 간단한 해결책은 .encode ()를 호출하여 바이트를 가져 오는 것입니다. 요즘에는 UTF-8이 필요할 수 있지만 수신자가 ASCII와 같은 특정 인코딩 (예 : 멀티 바이트 문자 없음)을 예상하는 경우이를 대신 사용하십시오.

    import io
    import tarfile
    
    data = 'hello\n'.encode('utf8')
    info = tarfile.TarInfo(name='foo.txt')
    info.size = len(data)
    
    with tarfile.TarFile('test.tar', 'w') as tar:
        tar.addfile(info, io.BytesIO(data))
    

    쓸만한 문자열 버퍼가 필요하다면, Python 2 용 @Stefano Borini의 대답과 유사하게 해결책은 기본 io.BytesIO 버퍼에 io.TextIOWrapper를 사용하는 것입니다.

    import io
    import tarfile
    
    textIO = io.TextIOWrapper(io.BytesIO(), encoding='utf8')
    textIO.write('hello\n')
    bytesIO = textIO.detach()
    info = tarfile.TarInfo(name='foo.txt')
    info.size = bytesIO.tell()
    
    with tarfile.TarFile('test.tar', 'w') as tar:
        bytesIO.seek(0)
        tar.addfile(info, bytesIO)
    
  8. from https://stackoverflow.com/questions/740820/python-write-string-directly-to-tarfile by cc-by-sa and MIT license