Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Accept Path objects as filename in IStructure.to() #3553

Merged
merged 2 commits into from
Jan 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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