¿Cómo envuelvo una cadena en un archivo en Python?


¿Cómo puedo crear un objeto similar a un archivo (mismo tipo de pato que un archivo) con el contenido de una cadena?

Author: A-B-B, 2008-09-26

4 answers

Para Python 2.x, utilice el módulo StringIO. Por ejemplo:

>>> from cStringIO import StringIO
>>> f = StringIO('foo')
>>> f.read()
'foo'

Uso cStringIO (que es más rápido), pero tenga en cuenta que no acepta cadenas Unicode que no se pueden codificar como cadenas ASCII simples. (Puede cambiar a StringIO cambiando "from cStringIO" a "from StringIO".)

Para Python 3.x, usa el io módulo.

f = io.StringIO('foo')
 93
Author: Daryl Spitzer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-31 17:26:02

En Python 3.0:

import io

with io.StringIO() as f:
    f.write('abcdef')
    print('gh', file=f)
    f.seek(0)
    print(f.read())
 23
Author: jfs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-26 22:00:25

Dos buenas respuestas. Añadiría un pequeño truco: si necesita un objeto de archivo real (algunos métodos esperan uno, no solo una interfaz), aquí hay una forma de crear un adaptador:

 2
Author: e-satis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-04-04 21:02:52

Esto funciona para Python2.7 y Python3.x:

io.StringIO(u'foo')
 1
Author: guettli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-27 15:02:22