Alexdd50 wrote: ↑Sat Feb 15, 2020 12:26 pm
My code is :
Code: Select all
for line in st.splitlines():
action ...
And the error :
Code: Select all
MemoryError: memory allocation failed, allocating %u bytes
What this code has to do is:
- Read the whole file into a string
- Make a new 1000-element list, and then create a short string for each line.
So the total memory used is 1000 * 4 + 2 * 1000 * N (where N is the average line length).
Instead what you want to do is use the built-in iterator on the file object:
Code: Select all
f = open('file.txt', 'r')
for line in f:
... do something with line
This will only use enough memory as it takes to store a single line of the file.