2010-11-18 16 views
6

Esiste qualche analogo di C# MemoryStream in Python (che potrebbe permettermi di scrivere dati binari da una fonte direttamente in memoria)? E come andrei a usarlo?MemoryStream analogico in Python

+0

Stai chiedendo di 'StringIO'? –

risposta

10

StringIO è una possibilità: http://docs.python.org/library/stringio.html

Questo modulo implementa una classe simile a file, StringIO, che legge e scrive un buffer stringa (noto anche come file di memoria). Vedere la descrizione degli oggetti file per le operazioni (sezione Oggetti file). (Per le stringhe standard, vedere str e unicode.) ...

+3

Oppure 'cStringIO', che è lo stesso ma è implementato in C per la velocità. –

3

Se si sta utilizzando Python> = 3.0 e provato Adam's answer, si noterà che import StringIO o import cStringIO sia dare un errore di importazione. Questo perché StringIO è now part of the io module.

Python 3.4.0 (default, Apr 11 2014, 13:05:11) 
[GCC 4.8.2] on linux 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import StringIO 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ImportError: No module named 'StringIO' 
>>> # Huh? Maybe this will work... 
... 
>>> import cStringIO 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ImportError: No module named 'cStringIO' 
>>> # Whaaaa...? 
... 
>>> import io 
>>> io.StringIO 
<class '_io.StringIO'> 
>>> # Oh, good! 
... 

È possibile utilizzare StringIO proprio come se fosse un file di Python regolare: write(), close(), e tutto ciò che il jazz, con un ulteriore getvalue() per recuperare la stringa.