逐行读取文件,而不是将文件读取到内存 [英] Read a file line-by-line instead of read file into memory
本文介绍了逐行读取文件,而不是将文件读取到内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在逐行读取文件时遇到了麻烦,而不是将文件读取到内存中.截至目前,我正在将文件读入内存,并且可以正常运行.但是,如果我尝试逐行读取文件,则在键入"print(B)"时只能得到零.我的问题是,有人在python中逐行读取文件吗?我的代码如下:
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. However, If i try to read the file line-by-line, I only get zero when I type 'print(B)'. My question is, does anyone have a good command for reading the file line-by-line in python? My code looks like this:
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')
推荐答案
这对您来说合适吗?
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)
这篇关于逐行读取文件,而不是将文件读取到内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文