From 9ff725dd287ff00cde87b64702ddc79caf5ddcf5 Mon Sep 17 00:00:00 2001 From: Shyue Ping Ong Date: Tue, 10 Dec 2024 18:21:22 -0800 Subject: [PATCH] =?UTF-8?q?Revert=20"`zopen`:=20explicit=20binary/text=20`?= =?UTF-8?q?mode`=20,=20and=20explicit=20`encoding`=20as=20UTF=E2=80=A6"=20?= =?UTF-8?q?(#4221)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit b2a5e0ffb441a66cf67ce72fbd926a40ef0f6703. --- dev_scripts/potcar_scrambler.py | 2 +- src/pymatgen/apps/borg/hive.py | 2 +- src/pymatgen/apps/borg/queen.py | 4 +- src/pymatgen/core/structure.py | 18 ++++---- src/pymatgen/core/trajectory.py | 2 +- src/pymatgen/io/adf.py | 2 +- src/pymatgen/io/aims/inputs.py | 4 +- src/pymatgen/io/cif.py | 8 ++-- src/pymatgen/io/common.py | 6 +-- src/pymatgen/io/core.py | 6 +-- src/pymatgen/io/cp2k/inputs.py | 2 +- src/pymatgen/io/cp2k/outputs.py | 16 +++---- src/pymatgen/io/cp2k/utils.py | 2 +- src/pymatgen/io/cssr.py | 4 +- src/pymatgen/io/exciting/inputs.py | 2 +- src/pymatgen/io/feff/inputs.py | 20 ++++---- src/pymatgen/io/feff/outputs.py | 10 ++-- src/pymatgen/io/fiesta.py | 16 +++---- src/pymatgen/io/gaussian.py | 12 ++--- src/pymatgen/io/lammps/data.py | 4 +- src/pymatgen/io/lammps/generators.py | 2 +- src/pymatgen/io/lammps/inputs.py | 4 +- src/pymatgen/io/lammps/outputs.py | 4 +- src/pymatgen/io/lmto.py | 6 +-- src/pymatgen/io/lobster/inputs.py | 4 +- src/pymatgen/io/lobster/outputs.py | 30 ++++++------ src/pymatgen/io/nwchem.py | 6 +-- src/pymatgen/io/pwmat/inputs.py | 10 ++-- src/pymatgen/io/pwmat/outputs.py | 6 +-- src/pymatgen/io/pwscf.py | 2 +- src/pymatgen/io/qchem/inputs.py | 6 +-- src/pymatgen/io/qchem/outputs.py | 2 +- src/pymatgen/io/qchem/sets.py | 2 +- src/pymatgen/io/res.py | 4 +- src/pymatgen/io/template.py | 2 +- src/pymatgen/io/vasp/inputs.py | 28 +++++------ src/pymatgen/io/vasp/outputs.py | 46 +++++++++---------- src/pymatgen/io/xr.py | 4 +- src/pymatgen/io/xyz.py | 4 +- src/pymatgen/io/zeopp.py | 4 +- .../transformations/site_transformations.py | 4 +- src/pymatgen/util/io_utils.py | 2 +- tests/electronic_structure/test_dos.py | 2 +- tests/io/aims/conftest.py | 2 +- tests/io/pwmat/test_inputs.py | 6 +-- tests/io/vasp/test_inputs.py | 2 +- tests/io/vasp/test_outputs.py | 2 +- 47 files changed, 170 insertions(+), 168 deletions(-) diff --git a/dev_scripts/potcar_scrambler.py b/dev_scripts/potcar_scrambler.py index 4a5bb292a82..23cd1403eb9 100644 --- a/dev_scripts/potcar_scrambler.py +++ b/dev_scripts/potcar_scrambler.py @@ -124,7 +124,7 @@ def scramble_single_potcar(self, potcar: PotcarSingle) -> str: return scrambled_potcar_str def to_file(self, filename: str) -> None: - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, mode="wt") as file: file.write(self.scrambled_potcars_str) @classmethod diff --git a/src/pymatgen/apps/borg/hive.py b/src/pymatgen/apps/borg/hive.py index fbd2a15645e..7045438fb81 100644 --- a/src/pymatgen/apps/borg/hive.py +++ b/src/pymatgen/apps/borg/hive.py @@ -445,7 +445,7 @@ def _get_transformation_history(path: PathLike): """Check for a transformations.json* file and return the history.""" if trans_json := glob(f"{path!s}/transformations.json*"): try: - with zopen(trans_json[0], mode="rt", encoding="utf-8") as file: + with zopen(trans_json[0]) as file: return json.load(file)["history"] except Exception: return None diff --git a/src/pymatgen/apps/borg/queen.py b/src/pymatgen/apps/borg/queen.py index bfa47b39432..2dd4d74e03a 100644 --- a/src/pymatgen/apps/borg/queen.py +++ b/src/pymatgen/apps/borg/queen.py @@ -103,12 +103,12 @@ def save_data(self, filename: PathLike) -> None: that if the filename ends with gz or bz2, the relevant gzip or bz2 compression will be applied. """ - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, mode="wt") as file: json.dump(list(self._data), file, cls=MontyEncoder) def load_data(self, filename: PathLike) -> None: """Load assimilated data from a file.""" - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: self._data = json.load(file, cls=MontyDecoder) diff --git a/src/pymatgen/core/structure.py b/src/pymatgen/core/structure.py index 6d0cd6545ae..63c1445fc05 100644 --- a/src/pymatgen/core/structure.py +++ b/src/pymatgen/core/structure.py @@ -2953,7 +2953,7 @@ def to(self, filename: PathLike = "", fmt: FileFormats = "", **kwargs) -> str: elif fmt == "json" or fnmatch(filename.lower(), "*.json*"): json_str = json.dumps(self.as_dict()) if filename: - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, mode="wt") as file: file.write(json_str) return json_str elif fmt == "xsf" or fnmatch(filename.lower(), "*.xsf*"): @@ -2961,7 +2961,7 @@ def to(self, filename: PathLike = "", fmt: FileFormats = "", **kwargs) -> str: res_str = XSF(self).to_str() if filename: - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, mode="wt", encoding="utf8") as file: file.write(res_str) return res_str elif ( @@ -2987,7 +2987,7 @@ def to(self, filename: PathLike = "", fmt: FileFormats = "", **kwargs) -> str: yaml.dump(self.as_dict(), str_io) yaml_str = str_io.getvalue() if filename: - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, mode="wt") as file: file.write(yaml_str) return yaml_str elif fmt == "aims" or fnmatch(filename, "geometry.in"): @@ -2995,7 +2995,7 @@ def to(self, filename: PathLike = "", fmt: FileFormats = "", **kwargs) -> str: geom_in = AimsGeometryIn.from_structure(self) if filename: - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, mode="w") as file: file.write(geom_in.get_header(filename)) file.write(geom_in.content) file.write("\n") @@ -3010,7 +3010,7 @@ def to(self, filename: PathLike = "", fmt: FileFormats = "", **kwargs) -> str: res_str = ResIO.structure_to_str(self) if filename: - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, mode="wt", encoding="utf8") as file: file.write(res_str) return res_str elif fmt == "pwmat" or fnmatch(filename.lower(), "*.pwmat") or fnmatch(filename.lower(), "*.config"): @@ -3173,7 +3173,7 @@ def from_file( return struct fname = os.path.basename(filename) - with zopen(filename, mode="rt", errors="replace", encoding="utf-8") as file: + with zopen(filename, mode="rt", errors="replace") as file: contents = file.read() if fnmatch(fname.lower(), "*.cif*") or fnmatch(fname.lower(), "*.mcif*"): return cls.from_str( @@ -3919,7 +3919,7 @@ def to(self, filename: str = "", fmt: str = "") -> str | None: elif fmt == "json" or fnmatch(filename, "*.json*") or fnmatch(filename, "*.mson*"): json_str = json.dumps(self.as_dict()) if filename: - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, mode="wt", encoding="utf8") as file: file.write(json_str) return json_str elif fmt in {"yaml", "yml"} or fnmatch(filename, "*.yaml*") or fnmatch(filename, "*.yml*"): @@ -3928,7 +3928,7 @@ def to(self, filename: str = "", fmt: str = "") -> str | None: yaml.dump(self.as_dict(), str_io) yaml_str = str_io.getvalue() if filename: - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, mode="wt", encoding="utf8") as file: file.write(yaml_str) return yaml_str else: @@ -4010,7 +4010,7 @@ def from_file(cls, filename: PathLike) -> Self | None: """ filename = str(filename) - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename) as file: contents = file.read() fname = filename.lower() if fnmatch(fname, "*.xyz*"): diff --git a/src/pymatgen/core/trajectory.py b/src/pymatgen/core/trajectory.py index bc656711bb2..3e4d702998d 100644 --- a/src/pymatgen/core/trajectory.py +++ b/src/pymatgen/core/trajectory.py @@ -467,7 +467,7 @@ def write_Xdatcar( xdatcar_str = "\n".join(lines) + "\n" - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, mode="wt") as file: file.write(xdatcar_str) def as_dict(self) -> dict: diff --git a/src/pymatgen/io/adf.py b/src/pymatgen/io/adf.py index 6725c89beb6..f5fbf52d9a2 100644 --- a/src/pymatgen/io/adf.py +++ b/src/pymatgen/io/adf.py @@ -645,7 +645,7 @@ def _parse_logfile(self, logfile): # The last non-empty line of the logfile must match the end pattern. # Otherwise the job has some internal failure. The TAPE13 part of the # ADF manual has a detailed explanation. - with zopen(logfile, mode="rt", encoding="utf-8") as file: + with zopen(logfile, mode="rt") as file: for line in reverse_readline(file): if line == "": continue diff --git a/src/pymatgen/io/aims/inputs.py b/src/pymatgen/io/aims/inputs.py index fd8860deb2b..8304a6eb0d5 100644 --- a/src/pymatgen/io/aims/inputs.py +++ b/src/pymatgen/io/aims/inputs.py @@ -133,7 +133,7 @@ def from_file(cls, filepath: str | Path) -> Self: Returns: AimsGeometryIn: The input object represented in the file """ - with zopen(filepath, mode="rt", encoding="utf-8") as in_file: + with zopen(filepath, mode="rt") as in_file: content = in_file.read() return cls.from_str(content) @@ -753,7 +753,7 @@ def from_file(cls, filename: str, label: str | None = None) -> Self: Returns: AimsSpeciesFile """ - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: return cls(data=file.read(), label=label) @classmethod diff --git a/src/pymatgen/io/cif.py b/src/pymatgen/io/cif.py index 0bb6413402e..253f7d86372 100644 --- a/src/pymatgen/io/cif.py +++ b/src/pymatgen/io/cif.py @@ -299,7 +299,7 @@ def from_file(cls, filename: PathLike) -> Self: Returns: CifFile """ - with zopen(filename, mode="rt", errors="replace", encoding="utf-8") as file: + with zopen(filename, mode="rt", errors="replace") as file: return cls.from_str(file.read()) @@ -1760,9 +1760,9 @@ def cif_file(self) -> CifFile: def write_file( self, - filename: PathLike, - mode: Literal["wt", "at"] = "wt", + filename: str | Path, + mode: Literal["w", "a", "wt", "at"] = "w", ) -> None: """Write the CIF file.""" - with zopen(filename, mode=mode, encoding="utf-8") as file: + with zopen(filename, mode=mode) as file: file.write(str(self)) diff --git a/src/pymatgen/io/common.py b/src/pymatgen/io/common.py index 6a99f044b1a..abaf3c9e4c5 100644 --- a/src/pymatgen/io/common.py +++ b/src/pymatgen/io/common.py @@ -354,7 +354,7 @@ def to_cube(self, filename, comment: str = ""): filename (str): Name of the cube file to be written. comment (str): If provided, this will be added to the second comment line """ - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, mode="wt") as file: file.write(f"# Cube file for {self.structure.formula} generated by Pymatgen\n") file.write(f"# {comment}\n") file.write(f"\t {len(self.structure)} 0.000000 0.000000 0.000000\n") @@ -386,7 +386,7 @@ def from_cube(cls, filename: str | Path) -> Self: Args: filename (str): of the cube to read """ - file = zopen(filename, mode="rt", encoding="utf-8") + file = zopen(filename, mode="rt") # skip header lines file.readline() @@ -529,7 +529,7 @@ def __getitem__(self, item): f"No parser defined for {item}. Contents are returned as a string.", stacklevel=2, ) - with zopen(fpath, mode="rt", encoding="utf-8") as f: + with zopen(fpath, "rt") as f: return f.read() def get_files_by_name(self, name: str) -> dict[str, Any]: diff --git a/src/pymatgen/io/core.py b/src/pymatgen/io/core.py index e81cd7a026e..5484954afe1 100644 --- a/src/pymatgen/io/core.py +++ b/src/pymatgen/io/core.py @@ -74,7 +74,7 @@ def write_file(self, filename: PathLike) -> None: Args: filename: The filename to output to, including path. """ - with zopen(Path(filename), mode="wt", encoding="utf-8") as file: + with zopen(Path(filename), mode="wt") as file: file.write(self.get_str()) @classmethod @@ -102,7 +102,7 @@ def from_file(cls, path: PathLike) -> None: Returns: InputFile """ - with zopen(Path(path), mode="rt", encoding="utf-8") as file: + with zopen(Path(path), mode="rt") as file: return cls.from_str(file.read()) # from_str not implemented @@ -218,7 +218,7 @@ def write_input( if isinstance(contents, InputFile): contents.write_file(file_path) else: - with zopen(file_path, mode="wt", encoding="utf-8") as file: + with zopen(file_path, mode="wt") as file: file.write(str(contents)) if zip_inputs: diff --git a/src/pymatgen/io/cp2k/inputs.py b/src/pymatgen/io/cp2k/inputs.py index 488cd016771..aa68870f100 100644 --- a/src/pymatgen/io/cp2k/inputs.py +++ b/src/pymatgen/io/cp2k/inputs.py @@ -692,7 +692,7 @@ def _from_dict(cls, dct: dict): @classmethod def from_file(cls, filename: str | Path) -> Self: """Initialize from a file.""" - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: txt = preprocessor(file.read(), os.path.dirname(file.name)) return cls.from_str(txt) diff --git a/src/pymatgen/io/cp2k/outputs.py b/src/pymatgen/io/cp2k/outputs.py index 873301fe1df..a230d139baf 100644 --- a/src/pymatgen/io/cp2k/outputs.py +++ b/src/pymatgen/io/cp2k/outputs.py @@ -327,7 +327,7 @@ def parse_initial_structure(self): ) coord_table = [] - with zopen(self.filename, mode="rt", encoding="utf-8") as file: + with zopen(self.filename, mode="rt") as file: while True: line = file.readline() if re.search(r"Atom\s+Kind\s+Element\s+X\s+Y\s+Z\s+Z\(eff\)\s+Mass", line): @@ -789,7 +789,7 @@ def parse_atomic_kind_info(self): except (TypeError, IndexError, ValueError): atomic_kind_info[kind]["total_pseudopotential_energy"] = None - with zopen(self.filename, mode="rt", encoding="utf-8") as file: + with zopen(self.filename, mode="rt") as file: j = -1 lines = file.readlines() for k, line in enumerate(lines): @@ -1010,7 +1010,7 @@ def parse_mo_eigenvalues(self): eigenvalues = [] efermi = [] - with zopen(self.filename, mode="rt", encoding="utf-8") as file: + with zopen(self.filename, mode="rt") as file: lines = iter(file.readlines()) for line in lines: try: @@ -1349,7 +1349,7 @@ def parse_hyperfine(self, hyperfine_filename=None): else: return None - with zopen(hyperfine_filename, mode="rt", encoding="utf-8") as file: + with zopen(hyperfine_filename, mode="rt") as file: lines = [line for line in file.read().split("\n") if line] hyperfine = [[] for _ in self.ionic_steps] @@ -1370,7 +1370,7 @@ def parse_gtensor(self, gtensor_filename=None): else: return None - with zopen(gtensor_filename, mode="rt", encoding="utf-8") as file: + with zopen(gtensor_filename, mode="rt") as file: lines = [line for line in file.read().split("\n") if line] data = {} @@ -1407,7 +1407,7 @@ def parse_chi_tensor(self, chi_filename=None): else: return None - with zopen(chi_filename, mode="rt", encoding="utf-8") as file: + with zopen(chi_filename, mode="rt") as file: lines = [line for line in file.read().split("\n") if line] data = {k: [] for k in "chi_soft chi_local chi_total chi_total_ppm_cgs PV1 PV2 PV3 ISO ANISO".split()} @@ -1554,7 +1554,7 @@ def read_table_pattern( row_pattern, or a dict in case that named capturing groups are defined by row_pattern. """ - with zopen(self.filename, mode="rt", encoding="utf-8") as file: + with zopen(self.filename, mode="rt") as file: if strip: lines = file.readlines() text = "".join( @@ -1691,7 +1691,7 @@ def parse_pdos(dos_file=None, spin_channel=None, total=False): """ spin = Spin(spin_channel) if spin_channel else Spin.down if "BETA" in os.path.split(dos_file)[-1] else Spin.up - with zopen(dos_file, mode="rt", encoding="utf-8") as file: + with zopen(dos_file, mode="rt") as file: lines = file.readlines() kind = re.search(r"atomic kind\s(.*)\sat iter", lines[0]) or re.search(r"list\s(\d+)\s(.*)\sat iter", lines[0]) kind = kind.groups()[0] diff --git a/src/pymatgen/io/cp2k/utils.py b/src/pymatgen/io/cp2k/utils.py index 9566ce45fbe..7eca9758a73 100644 --- a/src/pymatgen/io/cp2k/utils.py +++ b/src/pymatgen/io/cp2k/utils.py @@ -80,7 +80,7 @@ def preprocessor(data: str, dir: str = ".") -> str: # noqa: A002 raise ValueError(f"length of inc should be 2, got {len(inc)}") inc = inc[1].strip("'") inc = inc.strip('"') - with zopen(os.path.join(dir, inc), mode="rt", encoding="utf-8") as file: + with zopen(os.path.join(dir, inc)) as file: data = re.sub(rf"{incl}", file.read(), data) variable_sets = re.findall(r"(@SET.+)", data, re.IGNORECASE) for match in variable_sets: diff --git a/src/pymatgen/io/cssr.py b/src/pymatgen/io/cssr.py index 1068396e14b..c5a4fa4ab82 100644 --- a/src/pymatgen/io/cssr.py +++ b/src/pymatgen/io/cssr.py @@ -57,7 +57,7 @@ def write_file(self, filename): Args: filename (str): Filename to write to. """ - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, mode="wt") as file: file.write(str(self) + "\n") @classmethod @@ -98,5 +98,5 @@ def from_file(cls, filename: str | Path) -> Self: Returns: Cssr object. """ - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: return cls.from_str(file.read()) diff --git a/src/pymatgen/io/exciting/inputs.py b/src/pymatgen/io/exciting/inputs.py index 5213c8f622a..7ef99482b03 100644 --- a/src/pymatgen/io/exciting/inputs.py +++ b/src/pymatgen/io/exciting/inputs.py @@ -172,7 +172,7 @@ def from_file(cls, filename: str | Path) -> Self: Returns: ExcitingInput """ - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: data = file.read().replace("\n", "") return cls.from_str(data) diff --git a/src/pymatgen/io/feff/inputs.py b/src/pymatgen/io/feff/inputs.py index 94ad04dd24e..d9365c25499 100644 --- a/src/pymatgen/io/feff/inputs.py +++ b/src/pymatgen/io/feff/inputs.py @@ -246,7 +246,7 @@ def header_string_from_file(filename: str = "feff.inp"): Returns: Reads header string. """ - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="r") as file: lines = file.readlines() feff_header_str = [] ln = 0 @@ -434,8 +434,8 @@ def atoms_string_from_file(filename): Returns: Atoms string. """ - with zopen(filename, mode="rt", encoding="utf-8") as file: - f = file.readlines() + with zopen(filename, mode="rt") as fobject: + f = fobject.readlines() coords = 0 atoms_str = [] @@ -527,7 +527,7 @@ def write_file(self, filename="ATOMS"): Args: filename: path for file to be written """ - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, mode="wt") as file: file.write(f"{self}\n") @@ -654,7 +654,7 @@ def write_file(self, filename="PARAMETERS"): Args: filename: filename and path to write to. """ - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, mode="wt") as file: file.write(f"{self}\n") @classmethod @@ -668,7 +668,7 @@ def from_file(cls, filename: str = "feff.inp") -> Self: Returns: Tags """ - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: lines = list(clean_lines(file.readlines())) params = {} eels_params = [] @@ -828,8 +828,8 @@ def pot_string_from_file(filename="feff.inp"): Returns: FEFFPOT string. """ - with zopen(filename, mode="rt", encoding="utf-8") as file: - f = file.readlines() + with zopen(filename, mode="rt") as f_object: + f = f_object.readlines() ln = -1 pot_str = ["POTENTIALS\n"] pot_tag = -1 @@ -934,7 +934,7 @@ def write_file(self, filename="POTENTIALS"): Args: filename: filename and path to write potential file to. """ - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, mode="wt") as file: file.write(str(self) + "\n") @@ -976,7 +976,7 @@ def __str__(self): def write_file(self, filename="paths.dat"): """Write paths.dat.""" - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, mode="wt") as file: file.write(str(self) + "\n") diff --git a/src/pymatgen/io/feff/outputs.py b/src/pymatgen/io/feff/outputs.py index 8357fdfd357..16a0de3567d 100644 --- a/src/pymatgen/io/feff/outputs.py +++ b/src/pymatgen/io/feff/outputs.py @@ -70,7 +70,7 @@ def from_file(cls, feff_inp_file: str = "feff.inp", ldos_file: str = "ldos") -> dos_index = 1 begin = 0 - with zopen(pot_inp, mode="rt", encoding="utf-8") as potfile: + with zopen(pot_inp, mode="r") as potfile: for line in potfile: if len(pot_read_end.findall(line)) > 0: break @@ -95,7 +95,7 @@ def from_file(cls, feff_inp_file: str = "feff.inp", ldos_file: str = "ldos") -> dicts = Potential.pot_dict_from_str(pot_string) pot_dict = dicts[0] - with zopen(f"{ldos_file}00.dat", mode="rt", encoding="utf-8") as file: + with zopen(f"{ldos_file}00.dat", mode="r") as file: lines = file.readlines() e_fermi = float(lines[0].split()[4]) @@ -172,7 +172,7 @@ def charge_transfer_from_file(feff_inp_file, ldos_file): pot_inp = re.sub(r"feff.inp", r"pot.inp", feff_inp_file) pot_readstart = re.compile(".*iz.*lmaxsc.*xnatph.*xion.*folp.*") pot_readend = re.compile(".*ExternalPot.*switch.*") - with zopen(pot_inp, mode="rt", encoding="utf-8") as potfile: + with zopen(pot_inp, mode="r") as potfile: for line in potfile: if len(pot_readend.findall(line)) > 0: break @@ -203,7 +203,7 @@ def charge_transfer_from_file(feff_inp_file, ldos_file): for idx in range(len(dicts[0]) + 1): if len(str(idx)) == 1: - with zopen(f"{ldos_file}0{idx}.dat", mode="rt", encoding="utf-8") as file: + with zopen(f"{ldos_file}0{idx}.dat", mode="rt") as file: lines = file.readlines() s = float(lines[3].split()[2]) p = float(lines[4].split()[2]) @@ -212,7 +212,7 @@ def charge_transfer_from_file(feff_inp_file, ldos_file): tot = float(lines[1].split()[4]) cht[str(idx)] = {pot_dict[idx]: {"s": s, "p": p, "d": d, "f": f1, "tot": tot}} else: - with zopen(f"{ldos_file}{idx}.dat", mode="rt", encoding="utf-8") as file: + with zopen(f"{ldos_file}{idx}.dat", mode="rt") as file: lines = file.readlines() s = float(lines[3].split()[2]) p = float(lines[4].split()[2]) diff --git a/src/pymatgen/io/fiesta.py b/src/pymatgen/io/fiesta.py index 5ed94ac3e69..df647a600fa 100644 --- a/src/pymatgen/io/fiesta.py +++ b/src/pymatgen/io/fiesta.py @@ -63,7 +63,7 @@ def run(self): init_folder = os.getcwd() os.chdir(self.folder) - with zopen(self.log_file, mode="wt", encoding="utf-8") as fout: + with zopen(self.log_file, mode="w") as fout: subprocess.call( [ self._NWCHEM2FIESTA_cmd, @@ -138,7 +138,7 @@ def _gw_run(self): if self.folder != init_folder: os.chdir(self.folder) - with zopen(self.log_file, mode="wt", encoding="utf-8") as fout: + with zopen(self.log_file, mode="w") as fout: subprocess.call( [ "mpirun", @@ -161,7 +161,7 @@ def bse_run(self): if self.folder != init_folder: os.chdir(self.folder) - with zopen(self.log_file, mode="wt", encoding="utf-8") as fout: + with zopen(self.log_file, mode="w") as fout: subprocess.call( [ "mpirun", @@ -214,7 +214,7 @@ def __init__(self, filename): """ self.filename = filename - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename) as file: basis_set = file.read() self.data = self._parse_file(basis_set) @@ -533,7 +533,7 @@ def write_file(self, filename: str | Path) -> None: Args: filename: Filename. """ - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, mode="w") as file: file.write(str(self)) def as_dict(self): @@ -712,7 +712,7 @@ def from_file(cls, filename: str | Path) -> Self: Returns: FiestaInput object """ - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename) as file: return cls.from_str(file.read()) @@ -730,7 +730,7 @@ def __init__(self, filename): """ self.filename = filename - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename) as file: data = file.read() chunks = re.split(r"GW Driver iteration", data) @@ -821,7 +821,7 @@ def __init__(self, filename): """ self.filename = filename - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename) as file: log_bse = file.read() # self.job_info = self._parse_preamble(preamble) diff --git a/src/pymatgen/io/gaussian.py b/src/pymatgen/io/gaussian.py index fd3ab518f4f..bfbd1938c7b 100644 --- a/src/pymatgen/io/gaussian.py +++ b/src/pymatgen/io/gaussian.py @@ -368,7 +368,7 @@ def from_file(cls, filename: str | Path) -> Self: Returns: GaussianInput object """ - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="r") as file: return cls.from_str(file.read()) def get_zmatrix(self): @@ -447,9 +447,9 @@ def para_dict_to_str(para, joiner=" "): def write_file(self, filename, cart_coords=False): """Write the input string into a file. - Option: see `__str__` method + Option: see __str__ method """ - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, mode="w") as file: file.write(self.to_str(cart_coords)) def as_dict(self): @@ -661,7 +661,7 @@ def _parse(self, filename): opt_structures = [] route_lower = {} - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: for line in file: if parse_stage == 0: if start_patt.search(line): @@ -1109,7 +1109,7 @@ def read_scan(self): data = {"energies": [], "coords": {}} # read in file - with zopen(self.filename, mode="rt", encoding="utf-8") as file: + with zopen(self.filename, mode="r") as file: line = file.readline() while line != "": @@ -1195,7 +1195,7 @@ def read_excitation_energies(self): transitions = [] # read in file - with zopen(self.filename, mode="rt", encoding="utf-8") as file: + with zopen(self.filename, mode="r") as file: line = file.readline() td = False while line != "": diff --git a/src/pymatgen/io/lammps/data.py b/src/pymatgen/io/lammps/data.py index 2e730c218ca..d0d565fb9f9 100644 --- a/src/pymatgen/io/lammps/data.py +++ b/src/pymatgen/io/lammps/data.py @@ -647,7 +647,7 @@ def from_file(cls, filename: str, atom_style: str = "full", sort_id: bool = Fals sort_id (bool): Whether sort each section by id. Default to True. """ - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: lines = file.readlines() kw_pattern = r"|".join(itertools.chain(*SECTION_KEYWORDS.values())) section_marks = [idx for idx, line in enumerate(lines) if re.search(kw_pattern, line)] @@ -1439,7 +1439,7 @@ def parse_xyz(cls, filename: str | Path) -> pd.DataFrame: Returns: pandas.DataFrame """ - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: lines = file.readlines() str_io = StringIO("".join(lines[2:])) # skip the 2nd line diff --git a/src/pymatgen/io/lammps/generators.py b/src/pymatgen/io/lammps/generators.py index d541dd1adf4..143860d8764 100644 --- a/src/pymatgen/io/lammps/generators.py +++ b/src/pymatgen/io/lammps/generators.py @@ -67,7 +67,7 @@ def get_input_set(self, structure: Structure | LammpsData | CombinedData) -> Lam data: LammpsData = LammpsData.from_structure(structure) if isinstance(structure, Structure) else structure # Load the template - with zopen(self.template, mode="rt", encoding="utf-8") as file: + with zopen(self.template, mode="r") as file: template_str = file.read() # Replace all variables diff --git a/src/pymatgen/io/lammps/inputs.py b/src/pymatgen/io/lammps/inputs.py index fa7987dfa3a..125261a903b 100644 --- a/src/pymatgen/io/lammps/inputs.py +++ b/src/pymatgen/io/lammps/inputs.py @@ -553,7 +553,7 @@ def write_file( If False, a single block is assumed. """ filename = filename if isinstance(filename, Path) else Path(filename) - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, mode="wt") as file: file.write(self.get_str(ignore_comments=ignore_comments, keep_stages=keep_stages)) @classmethod @@ -653,7 +653,7 @@ def from_file(cls, path: str | Path, ignore_comments: bool = False, keep_stages: LammpsInputFile """ filename = path if isinstance(path, Path) else Path(path) - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: return cls.from_str(file.read(), ignore_comments=ignore_comments, keep_stages=keep_stages) def __repr__(self) -> str: diff --git a/src/pymatgen/io/lammps/outputs.py b/src/pymatgen/io/lammps/outputs.py index 4efc01fc934..216cc458c66 100644 --- a/src/pymatgen/io/lammps/outputs.py +++ b/src/pymatgen/io/lammps/outputs.py @@ -115,7 +115,7 @@ def parse_lammps_dumps(file_pattern): files = sorted(files, key=lambda f: int(re.match(pattern, f)[1])) for filename in files: - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: dump_cache = [] for line in file: if line.startswith("ITEM: TIMESTEP"): @@ -144,7 +144,7 @@ def parse_lammps_log(filename: str = "log.lammps") -> list[pd.DataFrame]: Returns: [pd.DataFrame] containing thermo data for each completed run. """ - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: lines = file.readlines() begin_flag = ( "Memory usage per processor =", diff --git a/src/pymatgen/io/lmto.py b/src/pymatgen/io/lmto.py index a660ee12510..1a5d669d4bc 100644 --- a/src/pymatgen/io/lmto.py +++ b/src/pymatgen/io/lmto.py @@ -139,7 +139,7 @@ def write_file(self, filename="CTRL", **kwargs): """Write a CTRL file with structure, HEADER, and VERS that can be used as input for lmhart.run. """ - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, mode="wt") as file: file.write(self.get_str(**kwargs)) @classmethod @@ -153,7 +153,7 @@ def from_file(cls, filename: str | Path = "CTRL", **kwargs) -> Self: Returns: An LMTOCtrl object. """ - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: contents = file.read() return cls.from_str(contents, **kwargs) @@ -322,7 +322,7 @@ def __init__(self, filename="COPL", to_eV=False): eV, set to True. Defaults to False for energies in Ry. """ # COPL files have an extra trailing blank line - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: contents = file.read().split("\n")[:-1] # The parameters line is the second line in a COPL file. It # contains all parameters that are needed to map the file. diff --git a/src/pymatgen/io/lobster/inputs.py b/src/pymatgen/io/lobster/inputs.py index c83b57cfe4d..18a6a53c654 100644 --- a/src/pymatgen/io/lobster/inputs.py +++ b/src/pymatgen/io/lobster/inputs.py @@ -588,7 +588,7 @@ def from_file(cls, lobsterin: PathLike) -> Self: Returns: Lobsterin object """ - with zopen(lobsterin, mode="rt", encoding="utf-8") as file: + with zopen(lobsterin, mode="rt") as file: lines = file.read().split("\n") if not lines: raise RuntimeError("lobsterin file contains no data.") @@ -645,7 +645,7 @@ def _get_potcar_symbols(POTCAR_input: PathLike) -> list[str]: raise ValueError("Lobster only works with PAW! Use different POTCARs") # Warning about a bug in LOBSTER-4.1.0 - with zopen(POTCAR_input, mode="rt", encoding="utf-8") as file: + with zopen(POTCAR_input, mode="r") as file: data = file.read() if isinstance(data, bytes): diff --git a/src/pymatgen/io/lobster/outputs.py b/src/pymatgen/io/lobster/outputs.py index 90291feec7d..a0ca239bfe4 100644 --- a/src/pymatgen/io/lobster/outputs.py +++ b/src/pymatgen/io/lobster/outputs.py @@ -121,7 +121,7 @@ def __init__( else: self._filename = "COHPCAR.lobster" - with zopen(self._filename, mode="rt", encoding="utf-8") as file: + with zopen(self._filename, mode="rt") as file: lines = file.read().split("\n") # The parameters line is the second line in a COHPCAR file. @@ -405,7 +405,7 @@ def __init__( # LOBSTER list files have an extra trailing blank line # and we don't need the header. if self._icohpcollection is None: - with zopen(self._filename, mode="rt", encoding="utf-8") as file: + with zopen(self._filename, mode="rt") as file: all_lines = file.read().split("\n") lines = all_lines[1:-1] if "spin" not in all_lines[1] else all_lines[2:-1] if len(lines) == 0: @@ -622,7 +622,7 @@ def __init__(self, filename: PathLike | None = "NcICOBILIST.lobster") -> None: # LOBSTER list files have an extra trailing blank line # and we don't need the header - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: lines = file.read().split("\n")[1:-1] if len(lines) == 0: raise RuntimeError("NcICOBILIST file contains no data.") @@ -754,7 +754,7 @@ def _parse_doscar(self): tdensities = {} itdensities = {} - with zopen(doscar, mode="rt", encoding="utf-8") as file: + with zopen(doscar, mode="rt") as file: file.readline() # Skip the first line efermi = float([file.readline() for nn in range(4)][3].split()[17]) dos = [] @@ -913,7 +913,7 @@ def __init__( self.loewdin = [] if loewdin is None else loewdin if self.num_atoms is None: - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: lines = file.read().split("\n")[3:-3] if len(lines) == 0: raise RuntimeError("CHARGES file contains no data.") @@ -1047,7 +1047,7 @@ def __init__(self, filename: PathLike | None, **kwargs) -> None: else: raise ValueError(f"{attr}={val} is not a valid attribute for Lobsterout") elif filename: - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: lines = file.read().split("\n") if len(lines) == 0: raise RuntimeError("lobsterout does not contain any data") @@ -1445,7 +1445,7 @@ def __init__( raise ValueError("No FATBAND files in folder or given") for fname in filenames: - with zopen(fname, mode="rt", encoding="utf-8") as file: + with zopen(fname, mode="rt") as file: lines = file.read().split("\n") atom_names.append(os.path.split(fname)[1].split("_")[1].capitalize()) @@ -1479,7 +1479,7 @@ def __init__( eigenvals: dict = {} p_eigenvals: dict = {} for ifilename, filename in enumerate(filenames): - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: lines = file.read().split("\n") if ifilename == 0: @@ -1627,7 +1627,7 @@ def __init__( self.max_deviation = [] if max_deviation is None else max_deviation if not self.band_overlaps_dict: - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: lines = file.read().split("\n") spin_numbers = [0, 1] if lines[0].split()[-1] == "0" else [1, 2] @@ -1767,7 +1767,7 @@ def __init__( self.is_lcfo = is_lcfo self.list_dict_grosspop = [] if list_dict_grosspop is None else list_dict_grosspop if not self.list_dict_grosspop: - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: lines = file.read().split("\n") # Read file to list of dict @@ -1897,7 +1897,7 @@ def _parse_file( imaginary (list[float]): Imaginary parts of wave function. distance (list[float]): Distances to the first point in wave function file. """ - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: lines = file.read().split("\n") points = [] @@ -2067,7 +2067,7 @@ def __init__( self.madelungenergies_mulliken = None if madelungenergies_mulliken is None else madelungenergies_mulliken if self.ewald_splitting is None: - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: lines = file.read().split("\n")[5] if len(lines) == 0: raise RuntimeError("MadelungEnergies file contains no data.") @@ -2138,7 +2138,7 @@ def __init__( self.madelungenergies_mulliken: list | float = madelungenergies_mulliken or [] if self.num_atoms is None: - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: lines = file.read().split("\n") if len(lines) == 0: raise RuntimeError("SitePotentials file contains no data.") @@ -2291,7 +2291,7 @@ def __init__( """ self._filename = str(filename) - with zopen(self._filename, mode="rt", encoding="utf-8") as file: + with zopen(self._filename, mode="rt") as file: lines = file.readlines() if len(lines) == 0: raise RuntimeError("Please check provided input file, it seems to be empty") @@ -2479,7 +2479,7 @@ def __init__( self.bin_width = 0.0 if bin_width is None else bin_width if not self.bwdf: - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: lines = file.read().split("\n") if len(lines) == 0: raise RuntimeError("BWDF file contains no data.") diff --git a/src/pymatgen/io/nwchem.py b/src/pymatgen/io/nwchem.py index 523aa9a53a9..d9e4f47a463 100644 --- a/src/pymatgen/io/nwchem.py +++ b/src/pymatgen/io/nwchem.py @@ -394,7 +394,7 @@ def write_file(self, filename): Args: filename (str): Filename. """ - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, mode="w") as file: file.write(str(self)) def as_dict(self): @@ -534,7 +534,7 @@ def from_file(cls, filename: str | Path) -> Self: Returns: NwInput object """ - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename) as file: return cls.from_str(file.read()) @@ -557,7 +557,7 @@ def __init__(self, filename): """ self.filename = filename - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename) as file: data = file.read() chunks = re.split(r"NWChem Input Module", data) diff --git a/src/pymatgen/io/pwmat/inputs.py b/src/pymatgen/io/pwmat/inputs.py index 92bd77e0374..aa60c1737cd 100644 --- a/src/pymatgen/io/pwmat/inputs.py +++ b/src/pymatgen/io/pwmat/inputs.py @@ -36,7 +36,7 @@ def locate_all_lines(file_path: PathLike, content: str, exclusion: str = "") -> """ row_idxs: list[int] = [] # starts from 1 to be compatible with linecache package row_no: int = 0 - with zopen(file_path, mode="rt", encoding="utf-8") as file: + with zopen(file_path, mode="rt") as file: for row_content in file: row_no += 1 if content.upper() in row_content.upper() and ( @@ -418,7 +418,7 @@ def from_file(cls, filename: PathLike, mag: bool = False) -> Self: Returns: AtomConfig object. """ - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, "rt") as file: return cls.from_str(data=file.read(), mag=mag) @classmethod @@ -466,7 +466,7 @@ def get_str(self) -> str: def write_file(self, filename: PathLike, **kwargs): """Write AtomConfig to a file.""" - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, "wt") as file: file.write(self.get_str(**kwargs)) def as_dict(self): @@ -588,7 +588,7 @@ def write_file(self, filename: PathLike): Args: filename (PathLike): The absolute path of file to be written. """ - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, "wt") as file: file.write(self.get_str()) @@ -694,5 +694,5 @@ def get_hsp_row_str(label: str, index: int, coordinate: float) -> str: def write_file(self, filename: PathLike): """Write HighSymmetryPoint to a file.""" - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, "wt") as file: file.write(self.get_str()) diff --git a/src/pymatgen/io/pwmat/outputs.py b/src/pymatgen/io/pwmat/outputs.py index 0183be0bab7..9389e82befb 100644 --- a/src/pymatgen/io/pwmat/outputs.py +++ b/src/pymatgen/io/pwmat/outputs.py @@ -135,7 +135,7 @@ def _parse_sefv(self) -> list[dict]: 'atom_forces' and 'virial'. """ ionic_steps: list[dict] = [] - with zopen(self.filename, mode="rt", encoding="utf-8") as mvt: + with zopen(self.filename, "rt") as mvt: tmp_step: dict = {} for ii in range(self.n_ionic_steps): tmp_chunk: str = "" @@ -168,7 +168,7 @@ def __init__(self, filename: PathLike): filename (PathLike): The absolute path of OUT.FERMI file. """ self.filename: PathLike = filename - with zopen(self.filename, mode="rt", encoding="utf-8") as file: + with zopen(self.filename, "rt") as file: self._e_fermi: float = np.round(float(file.readline().split()[-2].strip()), 3) @property @@ -346,7 +346,7 @@ def _parse(self): labels: list[str] = [] labels = linecache.getline(str(self.filename), 1).split()[1:] dos_str: str = "" - with zopen(self.filename, mode="rt", encoding="utf-8") as file: + with zopen(self.filename, mode="rt") as file: file.readline() dos_str = file.read() dos: np.ndarray = np.loadtxt(StringIO(dos_str)) diff --git a/src/pymatgen/io/pwscf.py b/src/pymatgen/io/pwscf.py index 03f7e7d456e..2f32c0c346a 100644 --- a/src/pymatgen/io/pwscf.py +++ b/src/pymatgen/io/pwscf.py @@ -275,7 +275,7 @@ def from_file(cls, filename: str | Path) -> Self: Returns: PWInput object """ - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: return cls.from_str(file.read()) @classmethod diff --git a/src/pymatgen/io/qchem/inputs.py b/src/pymatgen/io/qchem/inputs.py index 7ff5be8487e..d350a84ba55 100644 --- a/src/pymatgen/io/qchem/inputs.py +++ b/src/pymatgen/io/qchem/inputs.py @@ -373,7 +373,7 @@ def write_multi_job_file(job_list: list[QCInput], filename: str): job_list (list[QCInput]): List of QChem jobs. filename (str): Name of the file to write. """ - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, mode="wt") as file: file.write(QCInput.multi_job_string(job_list)) @classmethod @@ -387,7 +387,7 @@ def from_file(cls, filename: str | Path) -> Self: Returns: QcInput """ - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: return cls.from_str(file.read()) @classmethod @@ -401,7 +401,7 @@ def from_multi_jobs_file(cls, filename: str) -> list[Self]: Returns: List of QCInput objects """ - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: # the delimiter between QChem jobs is @@@ multi_job_strings = file.read().split("@@@") # list of individual QChem jobs diff --git a/src/pymatgen/io/qchem/outputs.py b/src/pymatgen/io/qchem/outputs.py index d483e7ecba3..a3e9ad038a8 100644 --- a/src/pymatgen/io/qchem/outputs.py +++ b/src/pymatgen/io/qchem/outputs.py @@ -661,7 +661,7 @@ def multiple_outputs_from_file(filename, keep_sub_files=True): 2.) Creates separate QCCalcs for each one from the sub-files. """ to_return = [] - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: text = re.split(r"\s*(?:Running\s+)*Job\s+\d+\s+of\s+\d+\s+", file.read()) if text[0] == "": text = text[1:] diff --git a/src/pymatgen/io/qchem/sets.py b/src/pymatgen/io/qchem/sets.py index d68a1714218..dddd478a966 100644 --- a/src/pymatgen/io/qchem/sets.py +++ b/src/pymatgen/io/qchem/sets.py @@ -643,7 +643,7 @@ def write(self, input_file: PathLike) -> None: """ self.write_file(input_file) if self.smd_solvent in {"custom", "other"} and self.qchem_version == 5: - with zopen(os.path.join(os.path.dirname(input_file), "solvent_data"), mode="wt", encoding="utf-8") as file: + with zopen(os.path.join(os.path.dirname(input_file), "solvent_data"), mode="wt") as file: file.write(self.custom_smd) diff --git a/src/pymatgen/io/res.py b/src/pymatgen/io/res.py index cfc81f3d649..9a45a3b9dc2 100644 --- a/src/pymatgen/io/res.py +++ b/src/pymatgen/io/res.py @@ -249,7 +249,7 @@ def _parse_str(cls, source: str) -> Res: def _parse_file(cls, filename: str | Path) -> Res: """Parse the res file as a file.""" self = cls() - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="r") as file: self.source = file.read() return self._parse_txt() @@ -335,7 +335,7 @@ def string(self) -> str: def write(self, filename: str) -> None: """Write the res data to a file.""" - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, mode="w") as file: file.write(str(self)) diff --git a/src/pymatgen/io/template.py b/src/pymatgen/io/template.py index bacfd661e97..2ee08031ede 100644 --- a/src/pymatgen/io/template.py +++ b/src/pymatgen/io/template.py @@ -52,7 +52,7 @@ def get_input_set( self.filename = str(filename) # Load the template - with zopen(self.template, mode="rt", encoding="utf-8") as file: + with zopen(self.template, mode="r") as file: template_str = file.read() # Replace all variables diff --git a/src/pymatgen/io/vasp/inputs.py b/src/pymatgen/io/vasp/inputs.py index 11167289055..f5357b96dd7 100644 --- a/src/pymatgen/io/vasp/inputs.py +++ b/src/pymatgen/io/vasp/inputs.py @@ -285,7 +285,7 @@ def from_file( except Exception: names = None - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: return cls.from_str(file.read(), names, read_velocities=read_velocities) @classmethod @@ -671,7 +671,7 @@ def write_file(self, filename: PathLike, **kwargs) -> None: """Write POSCAR to a file. The supported kwargs are the same as those for the Poscar.get_str method and are passed through directly. """ - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, mode="wt") as file: file.write(self.get_str(**kwargs)) def as_dict(self) -> dict: @@ -906,7 +906,7 @@ def write_file(self, filename: PathLike) -> None: Args: filename (str): filename to write to. """ - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, mode="wt") as file: file.write(str(self)) @classmethod @@ -919,7 +919,7 @@ def from_file(cls, filename: PathLike) -> Self: Returns: Incar object """ - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: return cls.from_str(file.read()) @classmethod @@ -1659,7 +1659,7 @@ def from_file(cls, filename: PathLike) -> Self: Returns: Kpoints object """ - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: return cls.from_str(file.read()) @classmethod @@ -1800,7 +1800,7 @@ def write_file(self, filename: PathLike) -> None: Args: filename (PathLike): Filename to write to. """ - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, mode="wt") as file: file.write(str(self)) def as_dict(self) -> dict[str, Any]: @@ -2411,9 +2411,9 @@ def write_file(self, filename: str) -> None: """Write PotcarSingle to a file. Args: - filename (str): File to write to. + filename (str): Filename to write to. """ - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, mode="wt") as file: file.write(str(self)) def copy(self) -> Self: @@ -2438,7 +2438,7 @@ def from_file(cls, filename: PathLike) -> Self: symbol = match[0] if match else "" try: - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: return cls(file.read(), symbol=symbol or None) except UnicodeDecodeError: @@ -2850,7 +2850,7 @@ def from_file(cls, filename: PathLike) -> Self: Returns: Potcar """ - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: fdata = file.read() potcar = cls() @@ -2873,7 +2873,7 @@ def write_file(self, filename: PathLike) -> None: Args: filename (PathLike): filename to write to. """ - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, mode="wt") as file: file.write(str(self)) def set_symbols( @@ -3009,7 +3009,7 @@ def write_input( for key, value in self.items(): if value is not None: - with zopen(os.path.join(output_dir, key), mode="wt", encoding="utf-8") as file: + with zopen(os.path.join(output_dir, key), mode="wt") as file: file.write(str(value)) if cif_name: @@ -3032,8 +3032,8 @@ def write_input( files_to_transfer = files_to_transfer or {} for key, val in files_to_transfer.items(): with ( - zopen(val, mode="rb") as fin, - zopen(str(Path(output_dir) / key), mode="wb") as fout, + zopen(val, "rb") as fin, + zopen(str(Path(output_dir) / key), "wb") as fout, ): copyfileobj(fin, fout) diff --git a/src/pymatgen/io/vasp/outputs.py b/src/pymatgen/io/vasp/outputs.py index 33e76ec8cb2..4694183b8c5 100644 --- a/src/pymatgen/io/vasp/outputs.py +++ b/src/pymatgen/io/vasp/outputs.py @@ -312,7 +312,7 @@ def __init__( self.separate_spins = separate_spins self.exception_on_bad_xml = exception_on_bad_xml - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: if ionic_step_skip or ionic_step_offset: # Remove parts of the xml file and parse the string content: str = file.read() @@ -1772,7 +1772,7 @@ def __init__( self.occu_tol = occu_tol self.separate_spins = separate_spins - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: self.efermi = None parsed_header = False in_kpoints_opt = False @@ -2124,7 +2124,7 @@ def __init__(self, filename: PathLike) -> None: # Data from beginning of OUTCAR run_stats["cores"] = None - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: for line in file: if "serial" in line: # Activate serial parallelization @@ -2382,7 +2382,7 @@ def read_table_pattern( if last_one_only and first_one_only: raise ValueError("last_one_only and first_one_only options are incompatible") - with zopen(self.filename, mode="rt", encoding="utf-8") as file: + with zopen(self.filename, mode="rt") as file: text = file.read() table_pattern_text = header_pattern + r"\s*^(?P(?:\s+" + row_pattern + r")+)\s+" + footer_pattern table_pattern = re.compile(table_pattern_text, re.MULTILINE | re.DOTALL) @@ -2468,7 +2468,7 @@ def read_freq_dielectric(self) -> None: data: dict[str, Any] = {"REAL": [], "IMAGINARY": []} count = 0 component = "IMAGINARY" - with zopen(self.filename, mode="rt", encoding="utf-8") as file: + with zopen(self.filename, mode="rt") as file: for line in file: line = line.strip() if re.match(plasma_pattern, line): @@ -2594,7 +2594,7 @@ def read_cs_raw_symmetrized_tensors(self) -> None: row_pattern = r"\s+".join([r"([-]?\d+\.\d+)"] * 3) unsym_footer_pattern = r"^\s+SYMMETRIZED TENSORS\s+$" - with zopen(self.filename, mode="rt", encoding="utf-8") as file: + with zopen(self.filename, mode="rt") as file: text = file.read() unsym_table_pattern_text = header_pattern + first_part_pattern + r"(?P.+)" + unsym_footer_pattern table_pattern = re.compile(unsym_table_pattern_text, re.MULTILINE | re.DOTALL) @@ -3377,7 +3377,7 @@ def read_core_state_eigen(self) -> list[dict]: The core state eigenenergie of the 2s AO of the 6th atom of the structure at the last ionic step is [5]["2s"][-1]. """ - with zopen(self.filename, mode="rt", encoding="utf-8") as foutcar: + with zopen(self.filename, mode="rt") as foutcar: line = foutcar.readline() cl: list[dict] = [] @@ -3419,7 +3419,7 @@ def read_avg_core_poten(self) -> list[list]: The average core potential of the 2nd atom of the structure at the last ionic step is: [-1][1] """ - with zopen(self.filename, mode="rt", encoding="utf-8") as foutcar: + with zopen(self.filename, mode="rt") as foutcar: line = foutcar.readline() aps: list[list[float]] = [] while line != "": @@ -3615,7 +3615,7 @@ def parse_file(filename: PathLike) -> tuple[Poscar, dict, dict]: ngrid_pts = 0 data_count = 0 poscar = None - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: for line in file: original_line = line line = line.strip() @@ -3749,7 +3749,7 @@ def write_spin(data_type: str) -> None: if isinstance(data, Iterable): file.write("".join(data)) - with zopen(file_name, mode="wt", encoding="utf-8") as file: + with zopen(file_name, mode="wt") as file: poscar = Poscar(self.structure) # Use original name if it's been set (e.g. from Chgcar) @@ -4082,7 +4082,7 @@ def _read(self, filename: PathLike, parsed_kpoints: set[tuple[Kpoint]] | None = if parsed_kpoints is None: parsed_kpoints = set() - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file_handle: preamble_expr = re.compile(r"# of k-points:\s*(\d+)\s+# of bands:\s*(\d+)\s+# of ions:\s*(\d+)") kpoint_expr = re.compile(r"^k-point\s+(\d+).*weight = ([0-9\.]+)") band_expr = re.compile(r"^band\s+(\d+)") @@ -4113,7 +4113,7 @@ def _read(self, filename: PathLike, parsed_kpoints: set[tuple[Kpoint]] | None = # total and x,y,z) for each band, while non-SOC have only 1 list of projections: tot_count = 0 band_count = 0 - for line in file: + for line in file_handle: if total_expr.match(line): tot_count += 1 elif band_expr.match(line): @@ -4121,7 +4121,7 @@ def _read(self, filename: PathLike, parsed_kpoints: set[tuple[Kpoint]] | None = if band_count == 2: break - file.seek(0) # reset file handle to beginning + file_handle.seek(0) # reset file handle to beginning if tot_count == 1: is_soc = False elif tot_count == 4: @@ -4138,7 +4138,7 @@ def _read(self, filename: PathLike, parsed_kpoints: set[tuple[Kpoint]] | None = skipping_kpoint = False # true when skipping projections for a previously-parsed kpoint ion_line_count = 0 # printed twice when phase factors present proj_data_parsed_for_band = 0 # 0 for non-SOC, 1-4 for SOC/phase factors - for line in file: + for line in file_handle: line = line.strip() if ion_expr.match(line): ion_line_count += 1 @@ -4373,8 +4373,8 @@ def smart_convert(header: str, num: float | str) -> float | str: electronic_pattern = re.compile(r"\s*\w+\s*:(.*)") header: list = [] - with zopen(filename, mode="rt", encoding="utf-8") as file: - for line in file: + with zopen(filename, mode="rt") as fid: + for line in fid: if match := electronic_pattern.match(line.strip()): tokens = match[1].split() data = {header[idx]: smart_convert(header[idx], tokens[idx]) for idx in range(len(tokens))} @@ -4516,10 +4516,10 @@ def __init__( if ionicstep_end is not None and ionicstep_end < 1: raise ValueError("End ionic step cannot be less than 1") - file_len = sum(1 for _ in zopen(filename, mode="rt", encoding="utf-8")) + file_len = sum(1 for _ in zopen(filename, mode="rt")) ionicstep_cnt = 1 ionicstep_start = ionicstep_start or 0 - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: title = None for iline, line in enumerate(file): line = line.strip() @@ -4615,7 +4615,7 @@ def concatenate( raise ValueError("End ionic step cannot be less than 1") ionicstep_cnt = 1 - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: for line in file: line = line.strip() if preamble is None: @@ -4703,7 +4703,7 @@ def write_file(self, filename: PathLike, **kwargs) -> None: **kwargs: The same as those for the Xdatcar.get_str method and are passed through directly. """ - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, mode="wt") as file: file.write(self.get_str(**kwargs)) @@ -4725,7 +4725,7 @@ def __init__(self, filename: PathLike) -> None: Args: filename: Name of file containing DYNMAT. """ - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: lines = list(clean_lines(file.readlines())) self._nspecs, self._natoms, self._ndisps = map(int, lines[0].split()) self._masses = map(float, lines[1].split()) @@ -5420,7 +5420,7 @@ def __init__( self.occu_tol = occu_tol self.separate_spins = separate_spins - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="r") as file: self.ispin = int(file.readline().split()[-1]) # Remove useless header information @@ -5571,7 +5571,7 @@ def from_formatted(cls, filename: PathLike) -> Self: Returns: A Waveder object. """ - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: nspin, nkpts, nbands = file.readline().split() # 1 and 4 are the eigenvalues of the bands (this data is missing in the WAVEDER file) # 6:12 are the complex matrix elements in each cartesian direction. diff --git a/src/pymatgen/io/xr.py b/src/pymatgen/io/xr.py index e86554a83be..834b8d6d797 100644 --- a/src/pymatgen/io/xr.py +++ b/src/pymatgen/io/xr.py @@ -68,7 +68,7 @@ def write_file(self, filename: str | Path) -> None: Args: filename (str): name of the file to write to. """ - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, mode="wt") as file: file.write(str(self) + "\n") @classmethod @@ -155,5 +155,5 @@ def from_file(cls, filename: str | Path, use_cores: bool = True, thresh: float = xr (Xr): Xr object corresponding to the input file. """ - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: return cls.from_str(file.read(), use_cores=use_cores, thresh=thresh) diff --git a/src/pymatgen/io/xyz.py b/src/pymatgen/io/xyz.py index 4f44f66e552..98078baa63c 100644 --- a/src/pymatgen/io/xyz.py +++ b/src/pymatgen/io/xyz.py @@ -111,7 +111,7 @@ def from_file(cls, filename: str | Path) -> Self: Returns: XYZ object """ - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: return cls.from_str(file.read()) def as_dataframe(self): @@ -151,5 +151,5 @@ def write_file(self, filename: str) -> None: Args: filename (str): File name of output file. """ - with zopen(filename, mode="wt", encoding="utf-8") as file: + with zopen(filename, mode="wt") as file: file.write(str(self)) diff --git a/src/pymatgen/io/zeopp.py b/src/pymatgen/io/zeopp.py index 64f1557f4d1..55a1506dc44 100644 --- a/src/pymatgen/io/zeopp.py +++ b/src/pymatgen/io/zeopp.py @@ -146,7 +146,7 @@ def from_file(cls, filename: str | Path) -> Self: Returns: ZeoCssr object. """ - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="r") as file: return cls.from_str(file.read()) @@ -200,7 +200,7 @@ def from_file(cls, filename: str | Path) -> Self: Returns: XYZ object """ - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename) as file: return cls.from_str(file.read()) def __str__(self) -> str: diff --git a/src/pymatgen/transformations/site_transformations.py b/src/pymatgen/transformations/site_transformations.py index 6b1bede1f2a..4672bad1183 100644 --- a/src/pymatgen/transformations/site_transformations.py +++ b/src/pymatgen/transformations/site_transformations.py @@ -431,7 +431,9 @@ def apply_transformation(self, structure: Structure, return_ranked_list: bool | n_to_remove = round(n_to_remove) num_remove_dict[tuple(idx)] = n_to_remove n = len(idx) - total_combos += round(math.factorial(n) / math.factorial(n_to_remove) / math.factorial(n - n_to_remove)) + total_combos += int( + round(math.factorial(n) / math.factorial(n_to_remove) / math.factorial(n - n_to_remove)) + ) self.logger.debug(f"Total combinations = {total_combos}") diff --git a/src/pymatgen/util/io_utils.py b/src/pymatgen/util/io_utils.py index 7bf4efdc2f4..f8c7d268f43 100644 --- a/src/pymatgen/util/io_utils.py +++ b/src/pymatgen/util/io_utils.py @@ -81,7 +81,7 @@ def micro_pyawk(filename, search, results=None, debug=None, postdebug=None): for entry in search: entry[0] = re.compile(entry[0]) - with zopen(filename, mode="rt", encoding="utf-8") as file: + with zopen(filename, mode="rt") as file: for line in file: for entry in search: match = re.search(entry[0], line) diff --git a/tests/electronic_structure/test_dos.py b/tests/electronic_structure/test_dos.py index edf2c6957ae..a7c8dec41b1 100644 --- a/tests/electronic_structure/test_dos.py +++ b/tests/electronic_structure/test_dos.py @@ -108,7 +108,7 @@ class TestCompleteDos(TestCase): def setUp(self): with open(f"{TEST_DIR}/complete_dos.json") as file: self.dos = CompleteDos.from_dict(json.load(file)) - with zopen(f"{TEST_DIR}/pdag3_complete_dos.json.gz", mode="rt", encoding="utf-8") as file: + with zopen(f"{TEST_DIR}/pdag3_complete_dos.json.gz") as file: self.dos_pdag3 = CompleteDos.from_dict(json.load(file)) def test_get_gap(self): diff --git a/tests/io/aims/conftest.py b/tests/io/aims/conftest.py index b2ac971c904..3cabe2b3ca8 100644 --- a/tests/io/aims/conftest.py +++ b/tests/io/aims/conftest.py @@ -150,7 +150,7 @@ def compare_single_files(ref_file: PathLike, test_file: PathLike) -> None: with open(test_file) as tf: test_lines = tf.readlines()[5:] - with zopen(f"{ref_file}.gz", mode="rt", encoding="utf-8") as rf: + with zopen(f"{ref_file}.gz", mode="rt") as rf: ref_lines = rf.readlines()[5:] for test_line, ref_line in zip(test_lines, ref_lines, strict=True): diff --git a/tests/io/pwmat/test_inputs.py b/tests/io/pwmat/test_inputs.py index e1438482623..7618e7ecdf6 100644 --- a/tests/io/pwmat/test_inputs.py +++ b/tests/io/pwmat/test_inputs.py @@ -47,7 +47,7 @@ class TestACstrExtractor(PymatgenTest): def test_extract(self): filepath = f"{TEST_DIR}/atom.config" ac_extractor = ACExtractor(file_path=filepath) - with zopen(filepath, mode="rt", encoding="utf-8") as file: + with zopen(filepath, mode="rt") as file: ac_str_extractor = ACstrExtractor(atom_config_str="".join(file.readlines())) assert ac_extractor.n_atoms == ac_str_extractor.get_n_atoms() for idx in range(9): @@ -102,7 +102,7 @@ def test_write_file(self): tmp_file = f"{self.tmp_path}/gen.kpt.testing.lzma" gen_kpt.write_file(tmp_file) tmp_gen_kpt_str = "" - with zopen(tmp_file, mode="rt", encoding="utf-8") as file: + with zopen(tmp_file, mode="rt") as file: tmp_gen_kpt_str = file.read() assert gen_kpt.get_str() == tmp_gen_kpt_str @@ -128,7 +128,7 @@ def test_write_file(self): tmp_filepath = f"{self.tmp_path}/HIGH_SYMMETRY_POINTS.testing.lzma" high_symmetry_points.write_file(tmp_filepath) tmp_high_symmetry_points_str = "" - with zopen(tmp_filepath, "rt", encoding="utf-8") as file: + with zopen(tmp_filepath, "rt") as file: tmp_high_symmetry_points_str = file.read() assert tmp_high_symmetry_points_str == high_symmetry_points.get_str() diff --git a/tests/io/vasp/test_inputs.py b/tests/io/vasp/test_inputs.py index 5b572d44acd..1616ff4e5e7 100644 --- a/tests/io/vasp/test_inputs.py +++ b/tests/io/vasp/test_inputs.py @@ -1560,7 +1560,7 @@ def test_from_file(self): } def test_potcar_map(self): - fe_potcar = zopen(f"{FAKE_POTCAR_DIR}/POT_GGA_PAW_PBE/POTCAR.Fe_pv.gz", mode="rt", encoding="utf-8").read() + fe_potcar = zopen(f"{FAKE_POTCAR_DIR}/POT_GGA_PAW_PBE/POTCAR.Fe_pv.gz").read().decode("utf-8") # specify V instead of Fe - this makes sure the test won't pass if the # code just grabs the POTCAR from the config file (the config file would # grab the V POTCAR) diff --git a/tests/io/vasp/test_outputs.py b/tests/io/vasp/test_outputs.py index 8044a130e55..837884c22f0 100644 --- a/tests/io/vasp/test_outputs.py +++ b/tests/io/vasp/test_outputs.py @@ -2164,7 +2164,7 @@ def test_consistency(self): wder_ref = np.loadtxt(f"{VASP_OUT_DIR}/WAVEDERF.Si.gz", skiprows=1) def _check(wder): - with zopen(f"{VASP_OUT_DIR}/WAVEDERF.Si.gz", mode="rt", encoding="utf-8") as file: + with zopen(f"{VASP_OUT_DIR}/WAVEDERF.Si.gz") as file: first_line = [int(a) for a in file.readline().split()] assert wder.nkpoints == first_line[1] assert wder.nbands == first_line[2]