我正在处理大数据,因此找到一种读取数据的好方法非常重要。
我只是对不同的阅读方法有点困惑。
1.f=gzip.open(file,'r')
for line in f:
process line
#how can I process nth line? can I?
2.f=gzip.open(file,'r').readlines()
#f is a list
f[10000]
#we can process nth line
3.f=gzip.open(file,'r')
while True:
linelist=list(islice(f,4))
4.for line in fileinput.input():
process line
2 和 3 有什么区别?我只是发现他们的内存使用量是相同的。 islice() 还需要首先将整个文件加载到内存中(但稍后会一点一点地加载)。
而且我听说第四种方法是最不消耗内存的,它确实是一点一点地处理,对吗?
对于 10GB 规模的文件,您会推荐哪种文件读取方法?欢迎任何想法/信息。
谢谢
编辑:我认为我的问题之一是我有时需要随机挑选特定的行。
说:
f1=open(inputfile1, 'r')
while True:
line_group1 = list(islice(f1, 3))
if not line_group1:
break
#then process specific lines say, the second line.
processed 2nd line
if ( ....):
LIST1.append(line_group1[0])
LIST1.append(processed 2nd line)
LIST1.append(line_group1[2])
然后……喜欢
with open(file,'r') as f,
for line in f:
# process line
可能不起作用,我是对的吗?