Skip to content

Commit

Permalink
Accept Path objects as filename in IStructure.to() (#3553)
Browse files Browse the repository at this point in the history
* accept Path objects as filename in IStructure.to()

* add test case for saving structure to pathlib.Path
  • Loading branch information
janosh authored Jan 15, 2024
1 parent db20521 commit 2ec68d7
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 2 deletions.
4 changes: 2 additions & 2 deletions pymatgen/core/structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -2653,7 +2653,7 @@ def from_dict(cls, d: dict[str, Any], fmt: Literal["abivars"] | None = None) ->
charge = d.get("charge")
return cls.from_sites(sites, charge=charge, properties=d.get("properties"))

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

if fmt == "cif" or fnmatch(filename.lower(), "*.cif*"):
from pymatgen.io.cif import CifWriter
Expand Down
5 changes: 5 additions & 0 deletions tests/core/test_structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -868,6 +868,11 @@ def test_to_from_file_string(self):
# i.e. uses same merge_tol for site merging, same primitive=False, etc.
assert struct == CifParser(f"{TEST_FILES_DIR}/bad-unicode-gh-2947.mcif").parse_structures()[0]

# https://github.com/materialsproject/pymatgen/issues/3551
json_path = Path("test-with-path.json")
self.struct.to(filename=json_path)
assert os.path.isfile(json_path)

def test_to_file_alias(self):
out_path = f"{self.tmp_path}/POSCAR"
assert self.struct.to(out_path) == self.struct.to_file(out_path)
Expand Down

0 comments on commit 2ec68d7

Please sign in to comment.