MDAnalysis / mdanalysis

MDAnalysis is a Python library to analyze molecular dynamics simulations.
https://mdanalysis.org
Other
1.26k stars 641 forks source link

Add example for writing to NamedStream StringIO buffer #4583

Open hmacdope opened 2 months ago

hmacdope commented 2 months ago

We have plenty of examples of how to read a file from a StringIO buffer or similar using a NamedStream, but no examples of how to write to a StringIO buffer using a similar methodology. We should add a simple example like the following.

import MDAnalysis as mda
from io import StringIO

u = mda.Universe("pdb.pdb")
buf  = StringIO()
prot = u.select_atoms("protein")
with mda.Writer(mda.lib.util.NamedStream(buf, "prot.xyz"), prot.n_atoms) as w:
   w.write(prot)

buf.getvalue()
>>> # xyz file