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

后端 未结 4 1291
盖世英雄少女心
盖世英雄少女心 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)
    
    0 讨论(0)
  • 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))))
    
    0 讨论(0)
  • 2021-01-29 01:25

    Is this right for you?

    with open(filename, 'r') as f:
        data = f.readlines()
    
    A = sum(float(line) for line in data)
    B = sum(float(line)**2 for line in data)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题