Skip to content

Commit 6a82645

Browse files
STY: Apply ruff/flake8-simplify rule SIM115
SIM115 Use a context manager for opening files
1 parent 7b27198 commit 6a82645

File tree

4 files changed

+50
-62
lines changed

4 files changed

+50
-62
lines changed

Diff for: nipype/interfaces/fsl/model.py

+14-19
Original file line numberDiff line numberDiff line change
@@ -142,13 +142,12 @@ class Level1Design(BaseInterface):
142142
output_spec = Level1DesignOutputSpec
143143

144144
def _create_ev_file(self, evfname, evinfo):
145-
f = open(evfname, "w")
146-
for i in evinfo:
147-
if len(i) == 3:
148-
f.write(f"{i[0]:f} {i[1]:f} {i[2]:f}\n")
149-
else:
150-
f.write("%f\n" % i[0])
151-
f.close()
145+
with open(evfname, "w") as f:
146+
for i in evinfo:
147+
if len(i) == 3:
148+
f.write(f"{i[0]:f} {i[1]:f} {i[2]:f}\n")
149+
else:
150+
f.write("%f\n" % i[0])
152151

153152
def _create_ev_files(
154153
self,
@@ -403,9 +402,8 @@ def _run_interface(self, runtime):
403402
fsf_txt += cond_txt
404403
fsf_txt += fsf_postscript.substitute(overwrite=1)
405404

406-
f = open(os.path.join(cwd, "run%d.fsf" % i), "w")
407-
f.write(fsf_txt)
408-
f.close()
405+
with open(os.path.join(cwd, "run%d.fsf" % i), "w") as f:
406+
f.write(fsf_txt)
409407

410408
return runtime
411409

@@ -946,9 +944,8 @@ def _run_interface(self, runtime):
946944
for i, rundir in enumerate(ensure_list(self.inputs.feat_dirs)):
947945
fsf_txt += fsf_dirs.substitute(runno=i + 1, rundir=os.path.abspath(rundir))
948946
fsf_txt += fsf_footer.substitute()
949-
f = open(os.path.join(os.getcwd(), "register.fsf"), "w")
950-
f.write(fsf_txt)
951-
f.close()
947+
with open(os.path.join(os.getcwd(), "register.fsf"), "w") as f:
948+
f.write(fsf_txt)
952949

953950
return runtime
954951

@@ -1414,9 +1411,8 @@ def _run_interface(self, runtime):
14141411

14151412
# write design files
14161413
for i, name in enumerate(["design.mat", "design.con", "design.grp"]):
1417-
f = open(os.path.join(cwd, name), "w")
1418-
f.write(txt[name])
1419-
f.close()
1414+
with open(os.path.join(cwd, name), "w") as f:
1415+
f.write(txt[name])
14201416

14211417
return runtime
14221418

@@ -1583,9 +1579,8 @@ def _run_interface(self, runtime):
15831579
if ("fts" in key) and (nfcons == 0):
15841580
continue
15851581
filename = key.replace("_", ".")
1586-
f = open(os.path.join(cwd, filename), "w")
1587-
f.write(val)
1588-
f.close()
1582+
with open(os.path.join(cwd, filename), "w") as f:
1583+
f.write(val)
15891584

15901585
return runtime
15911586

Diff for: nipype/interfaces/nitime/analysis.py

+10-13
Original file line numberDiff line numberDiff line change
@@ -142,15 +142,13 @@ def _read_csv(self):
142142
143143
"""
144144
# Check that input conforms to expectations:
145-
first_row = open(self.inputs.in_file).readline()
145+
with open(self.inputs.in_file) as f:
146+
first_row = f.readline()
146147
if not first_row[1].isalpha():
147148
raise ValueError(
148149
"First row of in_file should contain ROI names as strings of characters"
149150
)
150-
151-
roi_names = (
152-
open(self.inputs.in_file).readline().replace('"', "").strip("\n").split(",")
153-
)
151+
roi_names = first_row.replace('"', "").strip("\n").split(",")
154152
# Transpose, so that the time is the last dimension:
155153
data = np.loadtxt(self.inputs.in_file, skiprows=1, delimiter=",").T
156154

@@ -255,16 +253,15 @@ def _make_output_files(self):
255253
tmp_f = tempfile.mkstemp()[1]
256254
np.savetxt(tmp_f, this[0], delimiter=",")
257255

258-
fid = open(
256+
with open(
259257
fname_presuffix(self.inputs.output_csv_file, suffix="_%s" % this[1]),
260258
"w+",
261-
)
262-
# this writes ROIs as header line
263-
fid.write("," + ",".join(self.ROIs) + "\n")
264-
# this writes ROI and data to a line
265-
for r, line in zip(self.ROIs, open(tmp_f)):
266-
fid.write(f"{r},{line}")
267-
fid.close()
259+
) as fid:
260+
# this writes ROIs as header line
261+
fid.write("," + ",".join(self.ROIs) + "\n")
262+
# this writes ROI and data to a line
263+
for r, line in zip(self.ROIs, open(tmp_f)):
264+
fid.write(f"{r},{line}")
268265

269266
def _make_output_figures(self):
270267
"""

Diff for: nipype/interfaces/slicer/generate_classes.py

+24-26
Original file line numberDiff line numberDiff line change
@@ -33,22 +33,22 @@ def force_to_valid_python_variable_name(old_name):
3333

3434
def add_class_to_package(class_codes, class_names, module_name, package_dir):
3535
module_python_filename = os.path.join(package_dir, "%s.py" % module_name)
36-
f_m = open(module_python_filename, "w")
37-
f_i = open(os.path.join(package_dir, "__init__.py"), "a+")
38-
f_m.write(
39-
"""# -*- coding: utf-8 -*-
36+
with (
37+
open(module_python_filename, "w") as f_m,
38+
open(os.path.join(package_dir, "__init__.py"), "a+") as f_i,
39+
):
40+
f_m.write(
41+
"""# -*- coding: utf-8 -*-
4042
\"\"\"Autogenerated file - DO NOT EDIT
4143
If you spot a bug, please report it on the mailing list and/or change the generator.\"\"\"\n\n"""
42-
)
43-
imports = """\
44+
)
45+
imports = """\
4446
from ..base import (CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec,
4547
File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath)
4648
import os\n\n\n"""
47-
f_m.write(imports)
48-
f_m.write("\n\n".join(class_codes))
49-
f_i.write("from {} import {}\n".format(module_name, ", ".join(class_names)))
50-
f_m.close()
51-
f_i.close()
49+
f_m.write(imports)
50+
f_m.write("\n\n".join(class_codes))
51+
f_i.write("from {} import {}\n".format(module_name, ", ".join(class_names)))
5252

5353

5454
def crawl_code_struct(code_struct, package_dir):
@@ -70,9 +70,8 @@ def crawl_code_struct(code_struct, package_dir):
7070
if l2:
7171
v = l2
7272
subpackages.append(k.lower())
73-
f_i = open(os.path.join(package_dir, "__init__.py"), "a+")
74-
f_i.write("from %s import *\n" % k.lower())
75-
f_i.close()
73+
with open(os.path.join(package_dir, "__init__.py"), "a+") as f_i:
74+
f_i.write("from %s import *\n" % k.lower())
7675
new_pkg_dir = os.path.join(package_dir, k.lower())
7776
if os.path.exists(new_pkg_dir):
7877
rmtree(new_pkg_dir)
@@ -88,9 +87,9 @@ def crawl_code_struct(code_struct, package_dir):
8887
list(v.values()), list(v.keys()), module_name, package_dir
8988
)
9089
if subpackages:
91-
f = open(os.path.join(package_dir, "setup.py"), "w")
92-
f.write(
93-
"""# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
90+
with open(os.path.join(package_dir, "setup.py"), "w") as f:
91+
f.write(
92+
"""# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
9493
# vi: set ft=python sts=4 ts=4 sw=4 et:
9594
def configuration(parent_package='',top_path=None):
9695
from numpy.distutils.misc_util import Configuration
@@ -105,16 +104,15 @@ def configuration(parent_package='',top_path=None):
105104
from numpy.distutils.core import setup
106105
setup(**configuration(top_path='').todict())
107106
""".format(
108-
pkg_name=package_dir.split("/")[-1],
109-
sub_pks="\n ".join(
110-
[
111-
"config.add_data_dir('%s')" % sub_pkg
112-
for sub_pkg in subpackages
113-
]
114-
),
107+
pkg_name=package_dir.split("/")[-1],
108+
sub_pks="\n ".join(
109+
[
110+
"config.add_data_dir('%s')" % sub_pkg
111+
for sub_pkg in subpackages
112+
]
113+
),
114+
)
115115
)
116-
)
117-
f.close()
118116

119117

120118
def generate_all_classes(

Diff for: tools/checkspecs.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -124,10 +124,8 @@ def _parse_module(self, uri):
124124
if filename is None:
125125
# nothing that we could handle here.
126126
return ([], [])
127-
f = open(filename)
128-
functions, classes = self._parse_lines(f, uri)
129-
f.close()
130-
return functions, classes
127+
with open(filename) as f:
128+
return self._parse_lines(f, uri)
131129

132130
def _parse_lines(self, linesource, module):
133131
"""Parse lines of text for functions and classes"""

0 commit comments

Comments
 (0)