Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 17th, 2012  |  syntax: None  |  size: 0.70 KB  |  hits: 15  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Python load 2GB of text file to memory
  2. >>> f = open('dump.xml','r')
  3. >>> dump = f.read()
  4.        
  5. Python(62813) malloc: *** mmap(size=140521659486208) failed (error code=12)
  6. *** error: can't allocate region
  7. *** set a breakpoint in malloc_error_break to debug
  8. Traceback (most recent call last):
  9.   File "<stdin>", line 1, in <module>
  10. MemoryError
  11.        
  12. import mmap
  13.  
  14. with open('dump.xml', 'rb') as f:
  15.   # Size 0 will read the ENTIRE file into memory!
  16.   m = mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ) #File is open read-only
  17.  
  18.   # Proceed with your code here -- note the file is already in memory
  19.   # so "readine" here will be as fast as could be
  20.   data = m.readline()
  21.   while data:
  22.     # Do stuff
  23.     data = m.readline()