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

后端 未结 4 1326
盖世英雄少女心
盖世英雄少女心 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条回答
  •  旧时难觅i
    2021-01-29 01:21

    Original problem is that you've hit the end of the file and need to go back to the start to iterate over it again. You can do this in a single iteration through the file, split into two and then sum.

    with open(filename) as f:
        A, B = map(sum, zip(*((x, x**2) for x in map(float, f))))
    

提交回复
热议问题