Read a file line-by-line instead of read file into memory

后端 未结 4 1294
盖世英雄少女心
盖世英雄少女心 2021-01-29 00:28

I´m having some trouble with reading a file line-by-line, instead of reading the the file into memory. As of right now, I\'m reading the file into memory, and it works perfect.

4条回答
  •  不知归路
    2021-01-29 01:32

    Here is a way to do it with only one pass over the file. You have to abandon the nice built-in sum and do it yourself:

    def read(filename):
        A, B = 0, 0
        with open(filename) as f:
            for line in f:
                x = float(line)
                A += x
                B += x**2
        print(A)
        print(B)
    

    Also note that you are actually iterating in a weird way over the lines of the file, since you have an outer loop for line in f and an inner loop in the sum that also runs over for line in f. Since f is an iterator, this means that the outer loop will only get to the first line, the inner loop will consume all other lines and sum them and then the outer loop has nothing else to process and quits. You should be able to see this by noting that the print(B) statement is only executed once.

提交回复
热议问题