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

后端 未结 4 1290
盖世英雄少女心
盖世英雄少女心 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:16

    To return to the beginning of the file, use seek:

    def read(filename):
    
        with open(filename, 'r') as f: #open the file
    
            A = sum(float(line) for line in f)
            f.seek(0)
            B = sum(float(line)**2 for line in f)
    
                print(B)
    

提交回复
热议问题