Skip to content

Commit 699fe00

Browse files
authored
Merge pull request #1621 from Anselmoo/Anselmoo/issue1620
refactor: ♻️ File I/O operations for better readability and maintainability
2 parents 6349d58 + 3ca511a commit 699fe00

9 files changed

+26
-32
lines changed

spectrafit/plugins/data_converter.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ def get_athena_column(fname: Path, comment: str = "#") -> Optional[List[str]]:
2828
Optional[List[str]]: The column names of the data file as a list.
2929
3030
"""
31-
with open(fname, encoding="utf-8") as f:
31+
with fname.open(encoding="utf-8") as f:
3232
data = f.read()
3333
lines = data.splitlines()
3434
return next(

spectrafit/plugins/file_converter.py

+5-8
Original file line numberDiff line numberDiff line change
@@ -109,20 +109,17 @@ def save(self, data: Any, fname: Path, export_format: str) -> None:
109109
)
110110

111111
if export_format == "json":
112-
with open(
113-
fname.with_suffix(f".{export_format}"), "w", encoding="utf-8"
112+
with fname.with_suffix(f".{export_format}").open(
113+
"w", encoding="utf-8"
114114
) as f:
115115
json.dump(data, f, indent=4)
116116
elif export_format in {"yaml", "yml"}:
117-
with open(
118-
fname.with_suffix(f".{export_format}"), "w", encoding="utf-8"
117+
with fname.with_suffix(f".{export_format}").open(
118+
"w", encoding="utf-8"
119119
) as f:
120120
yaml.dump(data, f, default_flow_style=False)
121121
elif export_format in {"toml", "lock"}:
122-
with open(
123-
fname.with_suffix(f".{export_format}"),
124-
"wb+",
125-
) as f:
122+
with fname.with_suffix(f".{export_format}").open("wb+") as f:
126123
tomli_w.dump(dict(**data), f)
127124

128125
def __call__(self) -> None:

spectrafit/plugins/notebook.py

+6-7
Original file line numberDiff line numberDiff line change
@@ -454,13 +454,12 @@ def export_report(self, report: Dict[Any, Any], args: FnameAPI) -> None:
454454
args (FnameAPI): Arguments for the file export including the path, prefix,
455455
and suffix.
456456
"""
457-
with open(
458-
self.fname2path(
459-
fname=args.fname,
460-
prefix=args.prefix,
461-
suffix=args.suffix,
462-
folder=args.folder,
463-
),
457+
with self.fname2path(
458+
fname=args.fname,
459+
prefix=args.prefix,
460+
suffix=args.suffix,
461+
folder=args.folder,
462+
).open(
464463
"wb+",
465464
) as f:
466465
tomli_w.dump(report, f)

spectrafit/plugins/pkl_converter.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ def to_numpy(self) -> None:
8282
def to_pickle(self) -> None:
8383
"""Export the data to a pickle file."""
8484
if self.export_format.lower() == "pkl":
85-
with open(self.fname, "wb") as f:
85+
with self.fname.open("wb") as f:
8686
pickle.dump(self.data, f)
8787
elif self.export_format.lower() == pkl_gz:
8888
with gzip.open(self.fname, "wb") as f:

spectrafit/plugins/pkl_visualizer.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -111,8 +111,8 @@ def save(self, data: Any, fname: Path, export_format: str) -> None:
111111
format=export_format,
112112
)
113113

114-
with open(
115-
pure_fname(fname).with_suffix(".json"), "w+", encoding="utf-8"
114+
with pure_fname(fname).with_suffix(".json").open(
115+
"w+", encoding="utf-8"
116116
) as outfile:
117117
json.dump(data, outfile, indent=4)
118118

spectrafit/plugins/pptx_converter.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -401,7 +401,7 @@ def convert(infile: Path, file_format: str) -> MutableMapping[str, Any]:
401401
f"File format '{infile.suffix}' is not supported; it must be '.lock'"
402402
)
403403

404-
with open(infile, "rb") as f:
404+
with infile.open("rb") as f:
405405
data = PPTXDataAPI(**tomli.load(f))
406406

407407
return {file_format: data}

spectrafit/plugins/rixs_converter.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -179,15 +179,13 @@ def save(self, data: Any, fname: Path, export_format: str) -> None:
179179
)
180180

181181
if export_format == "json":
182-
with open(
183-
pure_fname(fname).with_suffix(f".{export_format}"),
182+
with pure_fname(fname).with_suffix(f".{export_format}").open(
184183
"w",
185184
encoding="utf-8",
186185
) as f:
187186
json.dump(self.numpydict2listdict(data), f, indent=4)
188187
elif export_format in {"toml", "lock"}:
189-
with open(
190-
pure_fname(fname).with_suffix(f".{export_format}"),
188+
with pure_fname(fname).with_suffix(f".{export_format}").open(
191189
"wb",
192190
) as f:
193191
tomli_w.dump(self.numpydict2listdict(data), f, multiline_strings=False)

spectrafit/plugins/rixs_visualizer.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -637,10 +637,10 @@ def load_data(infile: Path) -> RIXSModelAPI:
637637
elif infile.suffix == ".npz":
638638
data = np.load(infile, allow_pickle=True)
639639
elif infile.suffix == ".json":
640-
with open(infile, encoding="utf-8") as f:
640+
with infile.open(encoding="utf-8") as f:
641641
data = json.load(f)
642642
elif infile.suffix in {".toml", ".lock"}:
643-
with open(infile, "rb") as f:
643+
with infile.open("rb") as f:
644644
data = tomli.load(f)
645645
else:
646646
raise ValueError(f"File type {infile.suffix} is not supported.")

spectrafit/tools.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -512,8 +512,8 @@ def save_as_csv(self) -> None:
512512
def save_as_json(self) -> None:
513513
"""Save the fitting result as json file."""
514514
if self.args["outfile"]:
515-
with open(
516-
Path(f"{self.args['outfile']}_summary.json"), "w", encoding="utf-8"
515+
with Path(f"{self.args['outfile']}_summary.json").open(
516+
"w", encoding="utf-8"
517517
) as f:
518518
json.dump(transform_nested_types(self.args), f, indent=4)
519519
else:
@@ -539,13 +539,13 @@ def read_input_file(fname: Path) -> MutableMapping[str, Any]:
539539
fname = Path(fname)
540540

541541
if fname.suffix == ".toml":
542-
with open(fname, "rb") as f:
542+
with fname.open("rb") as f:
543543
args = tomli.load(f)
544544
elif fname.suffix == ".json":
545-
with open(fname, encoding="utf-8") as f:
545+
with fname.open(encoding="utf-8") as f:
546546
args = json.load(f)
547547
elif fname.suffix in {".yaml", ".yml"}:
548-
with open(fname, encoding="utf-8") as f:
548+
with fname.open(encoding="utf-8") as f:
549549
args = yaml.load(f, Loader=yaml.FullLoader)
550550
else:
551551
raise OSError(
@@ -654,7 +654,7 @@ def pkl2any(pkl_fname: Path, encoding: str = "latin1") -> Any:
654654
with gzip.open(pkl_fname, "rb") as f:
655655
return unicode_check(f, encoding=encoding)
656656
elif pkl_fname.suffix == ".pkl":
657-
with open(pkl_fname, "rb") as f:
657+
with pkl_fname.open("rb") as f:
658658
return unicode_check(f, encoding=encoding)
659659
else:
660660
choices = [".pkl", ".pkl.gz"]

0 commit comments

Comments
 (0)