我在1GB RAM的Mac Mini上使用Python 2.6。我想读一个巨大的文本文件Python:如何将巨大的文本文件读入内存
$ ls -l links.csv; file links.csv; tail links.csv
-rw-r--r-- 1 user user 469904280 30 Nov 22:42 links.csv
links.csv: ASCII text, with CRLF line terminators
4757187,59883
4757187,99822
4757187,66546
4757187,638452
4757187,4627959
4757187,312826
4757187,6143
4757187,6141
4757187,3081726
4757187,58197
因此,文件中的每一行由一个由两个以逗号分隔的整数值的元组构成。 我想阅读整个文件并根据第二列进行排序。我知道,我可以在不将整个文件读入内存的情况下进行排序。但我认为一个500MB的文件,我应该仍然可以在内存中执行它,因为我有1GB可用。
但是,当我尝试读取文件时,Python似乎分配了比磁盘上的文件所需更多的内存。所以即使使用1GB的RAM,我也无法将500MB文件读入内存。 我的文件进行读取和打印一些信息有关的内存消耗Python代码是:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
infile=open("links.csv", "r")
edges=[]
count=0
#count the total number of lines in the file
for line in infile:
count=count+1
total=count
print "Total number of lines: ",total
infile.seek(0)
count=0
for line in infile:
edge=tuple(map(int,line.strip().split(",")))
edges.append(edge)
count=count+1
# for every million lines print memory consumption
if count%1000000==0:
print "Position: ", edge
print "Read ",float(count)/float(total)*100,"%."
mem=sys.getsizeof(edges)
for edge in edges:
mem=mem+sys.getsizeof(edge)
for node in edge:
mem=mem+sys.getsizeof(node)
print "Memory (Bytes): ", mem
我得到的输出是:
阅读只有25%的500MB的文件,巨蟒后Total number of lines: 30609720
Position: (9745, 2994)
Read 3.26693612356 %.
Memory (Bytes): 64348736
Position: (38857, 103574)
Read 6.53387224712 %.
Memory (Bytes): 128816320
Position: (83609, 63498)
Read 9.80080837067 %.
Memory (Bytes): 192553000
Position: (139692, 1078610)
Read 13.0677444942 %.
Memory (Bytes): 257873392
Position: (205067, 153705)
Read 16.3346806178 %.
Memory (Bytes): 320107588
Position: (283371, 253064)
Read 19.6016167413 %.
Memory (Bytes): 385448716
Position: (354601, 377328)
Read 22.8685528649 %.
Memory (Bytes): 448629828
Position: (441109, 3024112)
Read 26.1354889885 %.
Memory (Bytes): 512208580
已消耗500MB。因此,似乎将文件的内容存储为int整数列表并不是非常有效的内存。 有没有更好的方法来做到这一点,以便我可以将我的500MB文件读入我的1GB内存中?
我想与解释,像Python,你无法真正知道哪里是内存下去。然而,列表[通常 - 我不知道确切的python实现)需要比数组更多的内存,例如prev/next指针。 您可能需要使用C/C++来确切知道您使用了多少内存。 – Drakosha 2009-12-13 14:41:28
您将您的内存估计基于原始数据,但随后创建元组和整数。您可以看到,与短字符串相比,Python的实例开销在此处显而易见。您甚至可以将这些数据作为纯字符串进行排序,您是否尝试过? – u0b34a0f6ae 2009-12-13 14:42:30
我的记忆估计增加了整数,元组和列表的内存消耗。这是相当好的,它大致相同(减去Python解释器所消耗的内存),正如我在top中看到的那样。但我没有试图将数据作为纯字符串进行排序。我会怎么做? – asmaier 2009-12-13 14:57:14