Skip to content

Commit 2ec68d7

Browse files
authored
Accept Path objects as filename in IStructure.to() (#3553)
* accept Path objects as filename in IStructure.to() * add test case for saving structure to pathlib.Path
1 parent db20521 commit 2ec68d7

File tree

2 files changed

+7
-2
lines changed

2 files changed

+7
-2
lines changed

pymatgen/core/structure.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2653,7 +2653,7 @@ def from_dict(cls, d: dict[str, Any], fmt: Literal["abivars"] | None = None) ->
26532653
charge = d.get("charge")
26542654
return cls.from_sites(sites, charge=charge, properties=d.get("properties"))
26552655

2656-
def to(self, filename: str = "", fmt: str = "", **kwargs) -> str:
2656+
def to(self, filename: str | Path = "", fmt: str = "", **kwargs) -> str:
26572657
"""Outputs the structure to a file or string.
26582658
26592659
Args:
@@ -2673,7 +2673,7 @@ def to(self, filename: str = "", fmt: str = "", **kwargs) -> str:
26732673
str: String representation of molecule in given format. If a filename
26742674
is provided, the same string is written to the file.
26752675
"""
2676-
fmt = fmt.lower()
2676+
filename, fmt = str(filename), fmt.lower()
26772677

26782678
if fmt == "cif" or fnmatch(filename.lower(), "*.cif*"):
26792679
from pymatgen.io.cif import CifWriter

tests/core/test_structure.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -868,6 +868,11 @@ def test_to_from_file_string(self):
868868
# i.e. uses same merge_tol for site merging, same primitive=False, etc.
869869
assert struct == CifParser(f"{TEST_FILES_DIR}/bad-unicode-gh-2947.mcif").parse_structures()[0]
870870

871+
# https://github.com/materialsproject/pymatgen/issues/3551
872+
json_path = Path("test-with-path.json")
873+
self.struct.to(filename=json_path)
874+
assert os.path.isfile(json_path)
875+
871876
def test_to_file_alias(self):
872877
out_path = f"{self.tmp_path}/POSCAR"
873878
assert self.struct.to(out_path) == self.struct.to_file(out_path)

0 commit comments

Comments
 (0)