Quelle est la meilleure façon d’écrire le contenu d’un StringIO dans un fichier ?

StackOverflow https://stackoverflow.com/questions/3253258

  •  16-09-2020
  •  | 
  •  

Question

Quelle est la meilleure façon d'écrire le contenu d'un StringIO tampon dans un fichier ?

Je fais actuellement quelque chose comme :

buf = StringIO()
fd = open ('file.xml', 'w')
# populate buf
fd.write (buf.getvalue ())

Mais alors buf.getvalue () ferait-il une copie du contenu ?

Était-ce utile?

La solution

Utiliser shutdown.copyfileobj:

with open ('file.xml', 'w') as fd:
  buf.seek (0)
  shutil.copyfileobj (buf, fd)

ou shutil.copyfileobj (buf, fd, -1) pour copier à partir d'un objet fichier sans utiliser de morceaux de taille limitée (utilisé pour éviter une consommation de mémoire incontrôlée).

Autres conseils

Python3 :

from io import StringIO
...
with open('file.xml', mode='w') as f:
    print(buf.getvalue(), file=f)

Python 2.x :

from StringIO import StringIO
...
with open('file.xml', mode='w') as f:
    f.write(buf.getvalue())
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top