drSlump drSlump - 2 months ago 11
Python Question

Why a file cannot be read several times using the same handler?

I open several text file (STL) and run several operation on them using two functions previously defined. Precisely, the function "point_stl" extract the coordinates of the points contained in an STL file while the function "point_cloud" extracts the points from the STL files without repetitions.

with open(folder+"bone_set1.stl", "r") as f1, open(folder+"bone_set2.stl", "r") as f2:
var1 = point_stl(f1,f2)
var2 = point_cloud(f1,f2)

Why does it seem I can't use twice the variables f1 and f2? If I use them in the first function I don't get any results in the second and vice-versa.


Since you pass directly the file handlers, I assume that each function reads the files content.

Unfortunatly, after the first function has read the files, the read cursors are at the end of the files and the second function has nothing to read between the cursors and the end of the files.

My advice would be to:

  • first read the files outside the functions (before calling them)
  • then pass the files content to the function instead of the file handlers.

An other solution would be to set back the read cursors at the files start after the first function call.