From 20bcbddb03077681c5cfff9b83419d2f3c3582cf Mon Sep 17 00:00:00 2001 From: Andrew White Date: Mon, 27 Jul 2026 07:29:54 -0500 Subject: [PATCH] fix: input and output files are never closed --- mesh_to_tet.py | 61 +++++++++++++++++++++++++------------------------- 1 file changed, 30 insertions(+), 31 deletions(-) diff --git a/mesh_to_tet.py b/mesh_to_tet.py index e1d4132..1139285 100644 --- a/mesh_to_tet.py +++ b/mesh_to_tet.py @@ -23,37 +23,36 @@ def convert_mesh_to_tet(mesh_file_path, tet_output_path): """Convert a .mesh file to a .tet file.""" - mesh_file = open(mesh_file_path, "r") - tet_output = open(tet_output_path, "w") - - mesh_lines = list(mesh_file) - mesh_lines = [line.strip('\n') for line in mesh_lines] - vertices_start = mesh_lines.index('Vertices') - num_vertices = mesh_lines[vertices_start + 1] - - vertices = mesh_lines[vertices_start + 2:vertices_start + 2 - + int(num_vertices)] - - tetrahedra_start = mesh_lines.index('Tetrahedra') - num_tetrahedra = mesh_lines[tetrahedra_start + 1] - tetrahedra = mesh_lines[tetrahedra_start + 2:tetrahedra_start + 2 - + int(num_tetrahedra)] - - print("# Vertices, # Tetrahedra:", num_vertices, num_tetrahedra) - - # Write to tet output - tet_output.write("# Tetrahedral mesh generated using\n\n") - tet_output.write("# " + num_vertices + " vertices\n") - for v in vertices: - tet_output.write("v " + v + "\n") - tet_output.write("\n") - tet_output.write("# " + num_tetrahedra + " tetrahedra\n") - for t in tetrahedra: - line = t.split(' 0')[0] - line = line.split(" ") - line = [str(int(k) - 1) for k in line] - l_text = ' '.join(line) - tet_output.write("t " + l_text + "\n") + with open(mesh_file_path, "r") as mesh_file, open(tet_output_path, "w") as tet_output: + + mesh_lines = list(mesh_file) + mesh_lines = [line.strip('\n') for line in mesh_lines] + vertices_start = mesh_lines.index('Vertices') + num_vertices = mesh_lines[vertices_start + 1] + + vertices = mesh_lines[vertices_start + 2:vertices_start + 2 + + int(num_vertices)] + + tetrahedra_start = mesh_lines.index('Tetrahedra') + num_tetrahedra = mesh_lines[tetrahedra_start + 1] + tetrahedra = mesh_lines[tetrahedra_start + 2:tetrahedra_start + 2 + + int(num_tetrahedra)] + + print("# Vertices, # Tetrahedra:", num_vertices, num_tetrahedra) + + # Write to tet output + tet_output.write("# Tetrahedral mesh generated using\n\n") + tet_output.write("# " + num_vertices + " vertices\n") + for v in vertices: + tet_output.write("v " + v + "\n") + tet_output.write("\n") + tet_output.write("# " + num_tetrahedra + " tetrahedra\n") + for t in tetrahedra: + line = t.split(' 0')[0] + line = line.split(" ") + line = [str(int(k) - 1) for k in line] + l_text = ' '.join(line) + tet_output.write("t " + l_text + "\n") if __name__ == "__main__":