When I using the following code to read file:
lines=file("data.txt").read().split("\n")
I have the following error
MemoryError
the file size is
ls -l
-rw-r--r-- 1 charlie charlie 1258467201 Sep 26 12:57 data.txt
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Obviously the file is too large to be read into memory all at once.
Why not just use:
or, if you’re not on Python 2.6 and higher:
In both cases, you’ll get an iterator that can be treated much like a list of strings.
EDIT: Since your way of reading the entire file into one large string and then splitting it on newlines will remove the newlines in the process, I have added a
.rstrip("\n")to my examples in order to better simulate the result.