Skip to content

Commit 84cb119

Browse files
committed
MAINT: Explicitly pass the encoding when opening a file
1 parent d96a903 commit 84cb119

File tree

11 files changed

+22
-19
lines changed

11 files changed

+22
-19
lines changed

conftest.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def reload_qmflows() -> Generator[None, None, None]:
5454
def configure_plams_logger() -> "Generator[None, None, None]":
5555
"""Remove the date/time prefix from the PLAMS logging output."""
5656
# Ensure the plams.config dict is populated by firing up plams.init once
57-
with open(os.devnull, "w") as f1, tempfile.TemporaryDirectory() as f2:
57+
with open(os.devnull, "w", encoding="utf8") as f1, tempfile.TemporaryDirectory() as f2:
5858
with contextlib.redirect_stdout(f1), InitRestart(f2):
5959
pass
6060

src/qmflows/packages/_scm.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ def selected_atoms() -> None:
5858

5959
def inithess() -> None:
6060
hess_path = get_tmpfile_name("ADF_hessian_")
61-
hess_file = open(hess_path, "w")
61+
hess_file = open(hess_path, "w", encoding="utf8")
6262
hess_file.write(" ".join(['{:.6f}'.format(v) for v in value]))
6363
settings.specific[package].geometry.inithess = hess_path.as_posix()
6464

src/qmflows/parsers/_cp2k_basis_parser.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,5 +92,5 @@ def read_cp2k_basis(file: PathLike, *, allow_multiple_exponents: bool = False) -
9292
Whether to allow the parsing of basis sets consisting of multiple exponent sets.
9393
9494
"""
95-
with open(file, "r") as f:
95+
with open(file, "r", encoding="utf8") as f:
9696
return _read_basis(_BasisFileIter(f, start=1), allow_multiple_exponents)

src/qmflows/parsers/_cp2k_orbital_parser.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ def _find_mo_start(path: str | os.PathLike[str], unrestricted: bool) -> int | tu
9090
and a single integer otherwise.
9191
9292
"""
93-
with open(path, "r") as f:
93+
with open(path, "r", encoding="utf8") as f:
9494
# Find all headers, but skip restarts
9595
enumerator = enumerate((h.strip("MO| \n") for h in f), start=1)
9696
headers = [(i, h) for i, h in enumerator if "EIGENVALUES" in h]
@@ -153,7 +153,7 @@ def read_coefficients(
153153

154154
j0 = 0
155155
j1 = 0
156-
with open(path, "r") as f:
156+
with open(path, "r", encoding="utf8") as f:
157157
iterator = filter(None, (i.strip("MO| \n") for i in islice(f, start, None)))
158158
for h in iterator:
159159
# Each MO pair is preceded by their indices,
@@ -192,8 +192,8 @@ def read_coefficients(
192192

193193
def read_cp2k_number_of_orbitals(file_name: str | os.PathLike[str]) -> MO_metadata:
194194
"""Extract the number of (occupied) orbitals and basis functions."""
195-
with open(file_name, "r") as f:
196-
kwargs: "dict[str, list[int]]" = defaultdict(list)
195+
with open(file_name, "r", encoding="utf8") as f:
196+
kwargs: defaultdict[str, list[int]] = defaultdict(list)
197197
for line in f:
198198
match = _ORBITAL_PATTERN.search(line)
199199
if match is None:

src/qmflows/parsers/cp2k.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,7 @@ def read_cp2k_xyz(path: PathLike, dtype: DTypeLike = np.float64) -> NDArray[Any]
207207
Requires a CP2K ``*.xyz`` file.
208208
209209
"""
210-
with open(path, 'r') as f:
210+
with open(path, 'r', encoding="utf8") as f:
211211
n_atom = int(next(f))
212212
flat_iter = chain.from_iterable(_read_cp2k_xyz(f, n_atom))
213213
ret = np.fromiter(flat_iter, dtype=dtype)
@@ -238,7 +238,7 @@ def read_cp2k_table(
238238
**start**, **stop** and **step** can be used for specifiying the to-be parsed rows.
239239
240240
"""
241-
with open(path, 'r') as f:
241+
with open(path, 'r', encoding="utf8") as f:
242242
flat_iter = (i.split()[column] for i in islice(f, start, stop, step))
243243
return np.fromiter(flat_iter, dtype=dtype)
244244

@@ -261,7 +261,7 @@ def read_cp2k_table_slc(
261261
**start**, **stop** and **step** can be used for specifiying the to-be parsed rows.
262262
263263
"""
264-
with open(path, 'r') as f:
264+
with open(path, 'r', encoding="utf8") as f:
265265
clm_slc = slice(column_start, column_stop, column_step)
266266
row_slc = islice(f, row_start, row_stop, row_step)
267267
flat_iter = chain.from_iterable(i.split()[clm_slc] for i in row_slc)
@@ -300,7 +300,7 @@ def read_cp2k_pressure(
300300
major, _ = get_cp2k_version(path)
301301

302302
# Read the pressures
303-
with open(path, 'r') as f:
303+
with open(path, 'r', encoding="utf8") as f:
304304
iterator = _get_pressure_iter(major, f)
305305
return np.fromiter(islice(iterator, start, stop, step), dtype=dtype)
306306

@@ -313,7 +313,7 @@ def get_cp2k_version(out_file: PathLike) -> CP2KVersion:
313313
314314
Returns :code:`(0, 0)` if the versions cannot be identified.
315315
"""
316-
with open(out_file, 'r') as f:
316+
with open(out_file, 'r', encoding="utf8") as f:
317317
for i in f:
318318
i = i.strip()
319319
if i.startswith("CP2K| version string:"):

src/qmflows/parsers/utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ def try_search_pattern(
9898
) -> None | str:
9999
"""Search for an specific pattern in a file."""
100100
try:
101-
with open(file_name, 'r') as f:
101+
with open(file_name, 'r', encoding="utf8") as f:
102102
for line in f:
103103
if re.search(pat, line):
104104
return line

src/qmflows/test_utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ def _read_result_file(result: Result, extension: str, max_line: int = 100) -> No
195195
iterator = (os.path.join(root, i) for i in os.listdir(root)
196196
if os.path.splitext(i)[1] == extension)
197197
for i in iterator:
198-
with open(i, "r") as f:
198+
with open(i, "r", encoding="utf8") as f:
199199
ret_list = f.readlines()
200200
ret = "..." if len(ret_list) > max_line else ""
201201
ret += "".join(ret_list[-max_line:])

src/qmflows/utils.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,8 @@ def file_to_context(file: int | PathLike | IO[Any],
123123
"""
124124
# path-like object
125125
try:
126+
if "encoding" not in kwargs:
127+
kwargs["encoding"] = "utf8"
126128
return open(file, **kwargs) # type: ignore
127129

128130
# a file-like object (hopefully)
@@ -148,7 +150,8 @@ def init_restart(
148150
149151
"""
150152
is_init: bool = config.init
151-
with open(os.devnull, 'w') as f, redirect_stdout(f): # Temporary supress printing
153+
# Temporary supress printing
154+
with open(os.devnull, 'w', encoding="utf8") as f, redirect_stdout(f):
152155
init(path, folder)
153156

154157
# Parse variables

test/test_special_keywords.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,6 @@ def test_cp2k_mm_keywords():
294294
s.specific.cp2k.force_eval.mm.forcefield.parm_file_name = basename(
295295
s.specific.cp2k.force_eval.mm.forcefield.parm_file_name)
296296

297-
with open(PATH / 'cp2k_mm_special_keyword.yaml', 'rb') as f:
297+
with open(PATH / 'cp2k_mm_special_keyword.yaml', 'r', encoding="utf8") as f:
298298
ref = yaml2Settings(f)
299299
assertion.eq(s.specific, ref)

test/test_utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -98,9 +98,9 @@ def test_validate_status() -> None:
9898
validate_status(result)
9999
msg = str(rec.value)
100100

101-
with open(root / "cp2k_opt.out", "r") as f:
101+
with open(root / "cp2k_opt.out", "r", encoding="utf8") as f:
102102
out_ref = textwrap.indent("".join(f.readlines()[-100:]), 4 * " ")
103-
with open(root / "cp2k_opt.err", "r") as f:
103+
with open(root / "cp2k_opt.err", "r", encoding="utf8") as f:
104104
err_ref = textwrap.indent("".join(f.readlines()[-100:]), 4 * " ")
105105

106106
assertion.contains(msg, out_ref)

0 commit comments

Comments
 (0)