逐行读取文件而不是读取文件到内存中

时间:2018-03-13 15:03:08

标签: python file

我在逐行读取文件时遇到了一些麻烦,而不是将文件读入内存。截至目前,我正在将文件读入内存,并且它的工作非常完美。但是,如果我尝试逐行读取文件,当我输入'print(B)'时,我只会得到零。我的问题是,有没有人有一个很好的命令在python中逐行读取文件?我的代码如下所示:

def read(filename):

    with open(filename, 'r') as f: #open the file

        for line in f:

            A = sum(float(line) for line in f)

    with open(filename, 'r') as f:

            B = sum(float(line)**2 for line in f)

            print(B)

read('file.txt')

4 个答案:

答案 0 :(得分:3)

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.

答案 1 :(得分:1)

要返回文件的开头,请使用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)

答案 2 :(得分:1)

这适合你吗?

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)

答案 3 :(得分:0)

最初的问题是你已经到了文件的末尾,需要回到开头再次迭代它。您可以在文件的一次迭代中完成此操作,拆分为两个然后求和。

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