-1

i want to read in a 2 dimensional Gridworld and transform it into a 2D list of strings.

I used the open("filename") function to read in the file. My Code works but as soon as I print out the gridfile with the .read() function it does not work anymore. The Output is the Gridworld and empty lists ([''] and [['']]). If I remove the print statement it works perfectly fine.

Can anyone explain to me why this is the case? It seems like python has somehow "used" the file when calling the .read() function and is not able to call it twice...

grid_file = open("3by4.grid")

def transform_to_lists(grid_file):

  ***print(grid_file.read())***


  onedim_list = grid_file.read().split('\n')

  twodim_list = [i.split(' ') for i in onedim_list]

  return twodim_list

print (transform_to_lists(grid_file))
mayool
  • 138
  • 8
  • Using `read()` will move the read pointer to the end of the file. You have to reopen the file or use `seek()` to "rewind" it. – Klaus D. Jan 02 '18 at 16:29

1 Answers1

1

Your print statement already reads in the whole file and there is nothing more to read for your second attempt. If you need to first print the contents and then analyse, assign the contents to a variable.

a = grid_file.read()
print (a)
onedim_list = a.split('\n')

....
Hannu
  • 11,685
  • 4
  • 35
  • 51