0

This is a simplified version of my code. Basically I have a file of general format:

2 3 5
4 8 9
etc

for n lines, and I must organize the file into a dictionary. Before this, I need a sum of one of the data points, so I iterate through the file to create a sum first, then iterate back through each line again in a second for suite to create a nested dictionary data structure. But for some reason the second suite is completely ignored.

This is a simplified version, so obviously some things could be moved around, but in the real file I really do need two separate loops because one of the values is a percentage based on the total sum in the file which is only fully defined after the end of the first for loop.

file = open('file.txt', 'r')
dict = {}
for line in file:
    v1, v2, v3 = file.split(' ')
    sum += v1
for line in file:
    v1, v2, v3 = file.split(' ')
    key = v1
    subkey = v2
    ratio = v3/sum
    value = ratio
    dict[key] = [subkey],[value]
print(dict)

For some reason this just gives

{}

Which is taking the original assignment of the dictionary and ignoring the second for iteration. If I try to print anything in the second suite, like just v1, it is ignored. If I put it in the first for loop, it works.

user1251007
  • 15,891
  • 14
  • 50
  • 76
  • possible duplicate of [Why can't I call read() twice on an open file?](http://stackoverflow.com/questions/3906137/why-cant-i-call-read-twice-on-an-open-file) – jonrsharpe Sep 24 '14 at 07:36

1 Answers1

0

You would have to "rewind" the file handler to the beginning of the file.

When you open the file, the pointer is at the very beginning. Once the first for loop is finished, the pointer is at the end of the file. In the second for loop the pointer is still at the end, so it just does nothing.

By adding

file.seek(0)

just before the second for loop, the pointer is moved back to the beginning of the file, allowing you to read the file again from the beginning.

user1251007
  • 15,891
  • 14
  • 50
  • 76