from io import StringIO


def ase_to_xyz(atoms, comment="", file=True):
    """Convert ASE to xyz

    This function is useful to save xyz to DataFrame.
    """
    xyz = StringIO()
    symbols = atoms.get_chemical_symbols()
    natoms = len(symbols)
    xyz.write("%d\n%s\n" % (natoms, comment))

    for s, (x, y, z) in zip(symbols, atoms.positions):
        xyz.write("%-2s %22.15f %22.15f %22.15f\n" % (s, x, y, z))

    if file:
        return xyz
    else:
        return xyz.getvalue()