Skip to content

Commit

Permalink
style: Fix for-loop-writes (FURB122): Use of f.write in a for loop
Browse files Browse the repository at this point in the history
  • Loading branch information
echoix committed Jan 25, 2025
1 parent 739b15c commit bd8d98c
Show file tree
Hide file tree
Showing 18 changed files with 87 additions and 90 deletions.
6 changes: 2 additions & 4 deletions gui/wxpython/core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -862,12 +862,10 @@ def StoreEnvVariable(key, value=None, envFile=None):
return
expCmd = "set" if windows else "export"

for key, value in environ.items():
fd.write("%s %s=%s\n" % (expCmd, key, value))
fd.writelines("%s %s=%s\n" % (expCmd, key, value) for key, value in environ.items())

# write also skipped lines
for line in lineSkipped:
fd.write(line + os.linesep)
fd.writelines(line + os.linesep for line in lineSkipped)

fd.close()

Expand Down
8 changes: 4 additions & 4 deletions gui/wxpython/gcp/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -347,8 +347,9 @@ def SetSrcEnv(self, location, mapset):

try:
f = open(self.source_gisrc, mode="w")
for line in self.gisrc_dict.items():
f.write(line[0] + ": " + line[1] + "\n")
f.writelines(
line[0] + ": " + line[1] + "\n" for line in self.gisrc_dict.items()
)
finally:
f.close()

Expand Down Expand Up @@ -2769,8 +2770,7 @@ def MakeVGroup(self):

f = open(self.vgrpfile, mode="w")
try:
for vect in vgrouplist:
f.write(vect + "\n")
f.writelines(vect + "\n" for vect in vgrouplist)
finally:
f.close()

Expand Down
3 changes: 1 addition & 2 deletions gui/wxpython/gmodeler/panels.py
Original file line number Diff line number Diff line change
Expand Up @@ -683,8 +683,7 @@ def WriteModelFile(self, filename):
try:
mfile = open(filename, "w")
tmpfile.seek(0)
for line in tmpfile.readlines():
mfile.write(line)
mfile.writelines(tmpfile.readlines())
except OSError:
wx.MessageBox(
parent=self,
Expand Down
8 changes: 4 additions & 4 deletions gui/wxpython/image2target/ii2t_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -364,8 +364,9 @@ def SetSrcEnv(self, location, mapset):

try:
f = open(self.source_gisrc, mode="w")
for line in self.gisrc_dict.items():
f.write(line[0] + ": " + line[1] + "\n")
f.writelines(
line[0] + ": " + line[1] + "\n" for line in self.gisrc_dict.items()
)
finally:
f.close()

Expand Down Expand Up @@ -2709,8 +2710,7 @@ def MakeVGroup(self):

f = open(self.vgrpfile, mode="w")
try:
for vect in vgrouplist:
f.write(vect + "\n")
f.writelines(vect + "\n" for vect in vgrouplist)
finally:
f.close()

Expand Down
3 changes: 1 addition & 2 deletions gui/wxpython/lmgr/workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -448,8 +448,7 @@ def SaveToFile(self, filename):
try:
mfile = open(filename, "wb")
tmpfile.seek(0)
for line in tmpfile.readlines():
mfile.write(line)
mfile.writelines(tmpfile.readlines())
except OSError:
GError(
parent=self.lmgr,
Expand Down
5 changes: 3 additions & 2 deletions gui/wxpython/photo2image/ip2i_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,8 +255,9 @@ def SetSrcEnv(self, location, mapset):

try:
f = open(self.source_gisrc, mode="w")
for line in self.gisrc_dict.items():
f.write(line[0] + ": " + line[1] + "\n")
f.writelines(
line[0] + ": " + line[1] + "\n" for line in self.gisrc_dict.items()
)
finally:
f.close()

Expand Down
6 changes: 4 additions & 2 deletions gui/wxpython/wxplot/profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -446,8 +446,10 @@ def SaveProfileToFile(self, event):
dlg.Destroy()
return

for datapair in self.raster[r]["datalist"]:
fd.write("%.6f,%.6f\n" % (float(datapair[0]), float(datapair[1])))
fd.writelines(
"%.6f,%.6f\n" % (float(datapair[0]), float(datapair[1]))
for datapair in self.raster[r]["datalist"]
)

fd.close()

Expand Down
6 changes: 2 additions & 4 deletions lib/init/grass.py
Original file line number Diff line number Diff line change
Expand Up @@ -525,8 +525,7 @@ def write_gisrcrc(gisrcrc, gisrc, skip_variable=None):
del lines[number]
number += 1
with open(gisrcrc, "w") as f:
for line in lines:
f.write(line)
f.writelines(lines)


def read_env_file(path):
Expand All @@ -543,8 +542,7 @@ def write_gisrc(kv, filename, append=False):
# use append=True to avoid a race condition between write_gisrc() and
# grass_prompt() on startup (PR #548)
f = open(filename, "a" if append else "w")
for k, v in kv.items():
f.write("%s: %s\n" % (k, v))
f.writelines("%s: %s\n" % (k, v) for k, v in kv.items())
f.close()


Expand Down
12 changes: 6 additions & 6 deletions python/grass/gunittest/multireport.py
Original file line number Diff line number Diff line change
Expand Up @@ -413,13 +413,13 @@ def main_page(
)
)
page.write("</tbody></table>")
for image, caption in itertools.izip(images, captions):
page.write(
"<h3>{caption}<h3>"
'<img src="{image}" alt="{caption}" title="{caption}">'.format(
image=image, caption=caption
)
page.writelines(
"<h3>{caption}<h3>"
'<img src="{image}" alt="{caption}" title="{caption}">'.format(
image=image, caption=caption
)
for image, caption in itertools.izip(images, captions)
)
page.write("</body></html>")


Expand Down
14 changes: 8 additions & 6 deletions python/grass/gunittest/reporters.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,9 @@ def replace_in_file(file_path, pattern, repl):
# using tmp file to store the replaced content
tmp_file_path = file_path + ".tmp"
with open(file_path) as old_file, open(tmp_file_path, "w") as new_file:
for line in old_file:
new_file.write(re.sub(pattern=pattern, string=line, repl=repl))
new_file.writelines(
re.sub(pattern=pattern, string=line, repl=repl) for line in old_file
)
# remove old file since it must not exist for rename/move
os.remove(file_path)
# replace old file by new file
Expand Down Expand Up @@ -448,8 +449,7 @@ def wrap_stdstream_to_html(infile, outfile, module, stream):
after = "</pre></body></html>"
with open(outfile, "w") as html, open(infile) as text:
html.write(before)
for line in text:
html.write(color_error_line(html_escape(line)))
html.writelines(color_error_line(html_escape(line)) for line in text)
html.write(after)


Expand Down Expand Up @@ -795,8 +795,10 @@ def end_file_test(
file_index.write(files_section)

if supplementary_files:
for f in supplementary_files:
file_index.write('<li><a href="{f}">{f}</a></li>'.format(f=f))
file_index.writelines(
'<li><a href="{f}">{f}</a></li>'.format(f=f)
for f in supplementary_files
)

file_index.write("</ul>")

Expand Down
3 changes: 1 addition & 2 deletions raster/r.topidx/gridatb_to_arc.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,7 @@
NODATA_value 9999
"""
)
for inline in inf:
outf.write(inline)
outf.writelines(inf)

inf.close()
outf.close()
24 changes: 12 additions & 12 deletions scripts/d.polar/d.polar.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,10 +283,10 @@ def plot_eps(psout):

(x, y) = outercircle[1]
outf.write("%.2f %.2f moveto\n" % (x * scale + halfframe, y * scale + halfframe))
for x, y in outercircle[2:]:
outf.write(
"%.2f %.2f lineto\n" % (x * scale + halfframe, y * scale + halfframe)
)
outf.writelines(
"%.2f %.2f lineto\n" % (x * scale + halfframe, y * scale + halfframe)
for x, y in outercircle[2:]
)

t = string.Template(
"""
Expand Down Expand Up @@ -338,10 +338,10 @@ def plot_eps(psout):

(x, y) = sine_cosine_replic[1]
outf.write("%.2f %.2f moveto\n" % (x * scale + halfframe, y * scale + halfframe))
for x, y in sine_cosine_replic[2:]:
outf.write(
"%.2f %.2f lineto\n" % (x * scale + halfframe, y * scale + halfframe)
)
outf.writelines(
"%.2f %.2f lineto\n" % (x * scale + halfframe, y * scale + halfframe)
for x, y in sine_cosine_replic[2:]
)

t = string.Template(
"""
Expand All @@ -363,10 +363,10 @@ def plot_eps(psout):

(x, y) = vector[1]
outf.write("%.2f %.2f moveto\n" % (x * scale + halfframe, y * scale + halfframe))
for x, y in vector[2:]:
outf.write(
"%.2f %.2f lineto\n" % (x * scale + halfframe, y * scale + halfframe)
)
outf.writelines(
"%.2f %.2f lineto\n" % (x * scale + halfframe, y * scale + halfframe)
for x, y in vector[2:]
)

t = string.Template(
"""
Expand Down
3 changes: 1 addition & 2 deletions scripts/db.univar/db.univar.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,7 @@ def sortfile(infile, outfile):
for i in range(len(lines)):
lines[i] = float(lines[i].rstrip("\r\n"))
lines.sort()
for line in lines:
outf.write(str(line) + "\n")
outf.writelines(str(line) + "\n" for line in lines)

inf.close()
outf.close()
Expand Down
42 changes: 22 additions & 20 deletions scripts/g.extension/g.extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -1041,11 +1041,11 @@ def write_xml_modules(name, tree=None):
if bnode is not None:
file_.write("%s<binary>\n" % (" " * indent))
indent += 4
for fnode in bnode.findall("file"):
file_.write(
"%s<file>%s</file>\n"
% (" " * indent, os.path.join(options["prefix"], fnode.text))
)
file_.writelines(
"%s<file>%s</file>\n"
% (" " * indent, os.path.join(options["prefix"], fnode.text))
for fnode in bnode.findall("file")
)
indent -= 4
file_.write("%s</binary>\n" % (" " * indent))
file_.write('%s<libgis revision="%s" />\n' % (" " * indent, libgis_revison))
Expand Down Expand Up @@ -1091,20 +1091,22 @@ def write_xml_extensions(name, tree=None):
if bnode is not None:
file_.write("%s<binary>\n" % (" " * indent))
indent += 4
for fnode in bnode.findall("file"):
file_.write(
"%s<file>%s</file>\n"
% (" " * indent, os.path.join(options["prefix"], fnode.text))
)
file_.writelines(
"%s<file>%s</file>\n"
% (" " * indent, os.path.join(options["prefix"], fnode.text))
for fnode in bnode.findall("file")
)
indent -= 4
file_.write("%s</binary>\n" % (" " * indent))
# extension modules
mnode = tnode.find("modules")
if mnode is not None:
file_.write("%s<modules>\n" % (" " * indent))
indent += 4
for fnode in mnode.findall("module"):
file_.write("%s<module>%s</module>\n" % (" " * indent, fnode.text))
file_.writelines(
"%s<module>%s</module>\n" % (" " * indent, fnode.text)
for fnode in mnode.findall("module")
)
indent -= 4
file_.write("%s</modules>\n" % (" " * indent))

Expand Down Expand Up @@ -1136,14 +1138,14 @@ def write_xml_toolboxes(name, tree=None):
% (" " * indent, tnode.get("name"), tnode.get("code"))
)
indent += 4
for cnode in tnode.findall("correlate"):
file_.write(
'%s<correlate code="%s" />\n' % (" " * indent, tnode.get("code"))
)
for mnode in tnode.findall("task"):
file_.write(
'%s<task name="%s" />\n' % (" " * indent, mnode.get("name"))
)
file_.writelines(
'%s<correlate code="%s" />\n' % (" " * indent, tnode.get("code"))
for cnode in tnode.findall("correlate")
)
file_.writelines(
'%s<task name="%s" />\n' % (" " * indent, mnode.get("name"))
for mnode in tnode.findall("task")
)
indent -= 4
file_.write("%s</toolbox>\n" % (" " * indent))

Expand Down
3 changes: 1 addition & 2 deletions scripts/i.oif/i.oif.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,8 +146,7 @@ def main():
sys.stdout.write(fmt % (p + (v,)))
else:
outf = open(output, "w")
for v, p in oif:
outf.write(fmt % (p + (v,)))
outf.writelines(fmt % (p + (v,)) for v, p in oif)
outf.close()


Expand Down
12 changes: 4 additions & 8 deletions scripts/i.spectral/i.spectral.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,7 @@ def draw_gnuplot(what, xlabels, output, img_format, coord_legend):
outfile = os.path.join(tmp_dir, "data_%d" % i)
outf = open(outfile, "w")
xrange = max(xrange, len(row) - 2)
for j, val in enumerate(row[3:]):
outf.write("%d %s\n" % (j + 1, val))
outf.writelines("%d %s\n" % (j + 1, val) for j, val in enumerate(row[3:]))
outf.close()

# build gnuplot script
Expand Down Expand Up @@ -147,8 +146,7 @@ def draw_gnuplot(what, xlabels, output, img_format, coord_legend):

plotfile = os.path.join(tmp_dir, "spectrum.gnuplot")
plotf = open(plotfile, "w")
for line in lines:
plotf.write(line + "\n")
plotf.writelines(line + "\n" for line in lines)
plotf.close()

if output:
Expand All @@ -163,15 +161,13 @@ def draw_linegraph(what):
xfile = os.path.join(tmp_dir, "data_x")

xf = open(xfile, "w")
for j, val in enumerate(what[0][3:]):
xf.write("%d\n" % (j + 1))
xf.writelines("%d\n" % (j + 1) for j, val in enumerate(what[0][3:]))
xf.close()

for i, row in enumerate(what):
yfile = os.path.join(tmp_dir, "data_y_%d" % i)
yf = open(yfile, "w")
for j, val in enumerate(row[3:]):
yf.write("%s\n" % val)
yf.writelines("%s\n" % val for j, val in enumerate(row[3:]))
yf.close()
yfiles.append(yfile)

Expand Down
16 changes: 10 additions & 6 deletions scripts/v.in.mapgen/v.in.mapgen.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,10 @@ def main():
if f[0].lower() == "nan":
if points != []:
outf.write("L %d 1\n" % len(points))
for point in points:
outf.write(" %.15g %.15g %.15g\n" % tuple(map(float, point)))
outf.writelines(
" %.15g %.15g %.15g\n" % tuple(map(float, point))
for point in points
)
outf.write(" 1 %d\n" % cat)
cat += 1
points = []
Expand All @@ -134,8 +136,9 @@ def main():
if line[0] == "#":
if points != []:
outf.write("L %d 1\n" % len(points))
for point in points:
outf.write(" %.15g %.15g\n" % tuple(map(float, point)))
outf.writelines(
" %.15g %.15g\n" % tuple(map(float, point)) for point in points
)
outf.write(" 1 %d\n" % cat)
cat += 1
points = []
Expand All @@ -144,8 +147,9 @@ def main():

if points != []:
outf.write("L %d 1\n" % len(points))
for point in points:
outf.write(" %.15g %.15g\n" % tuple(map(float, point)))
outf.writelines(
" %.15g %.15g\n" % tuple(map(float, point)) for point in points
)
outf.write(" 1 %d\n" % cat)
cat += 1
outf.close()
Expand Down
Loading

0 comments on commit bd8d98c

Please sign in to comment.