Here’s a simple way to do the conversion and retain lattice information as the comment line in the xyz file. For more context, take a look at this forum post.
from pymatgen.core import Molecule
from mp_api.client import MPRester
import json
mpid = "mp-1227591"
with MPRester() as mpr:
structure = mpr.get_structure_by_material_id(mpid)
# perform operations on the structure here
lattice_comment = "# lattice = " + json.dumps(structure.lattice.matrix.tolist())
mol = Molecule(
structure.species,
structure.cart_coords,
charge = structure.charge,
site_properties=structure.site_properties,
)
xyz_str = mol.to(fmt="xyz")
xyz_lines = xyz_str.splitlines()
xyz_str = "\n".join([xyz_lines[0],lattice_comment,*xyz_lines[2:]])
with open(f"{mpid}.xyz","w") as f:
f.write(xyz_str)