1

I am opening a big CSV file and during inserting the data into the array I got MemoryError. So how can i read specific lines of that CSV file (for example from line 1 till 10000)

here is the code:

datafile=open('test.csv','r')
datareader=csv.reader(datafile,delimiter=';')

for row in datareader:
    MyArray.append(row)
3
  • How big is your csv file? Commented Sep 23, 2014 at 9:29
  • Why are you putting the lines into an array (list? np.array?), rather than just iterating over them? What are you trying to achieve? Commented Sep 23, 2014 at 9:30
  • The answer by Tim works well, it is more that 1GB, around 9 millions of line. I need the content of data in line (it is network packet) Commented Sep 23, 2014 at 9:38

2 Answers 2

2

I'd use islice instead of enumerate:

from itertools import islice

# First 10000
MyArray.extend(islice(datareader, 10000))

# Or, specify start/stop ranges (10000-20000 (non inclusive))
MyArray.extend(islice(datareader, 10000, 20000))

# Or read in chunks of 10k
for chunk in iter(lambda: list(islice(datareader, 10000)), []):
    # do something with 10k rows
Sign up to request clarification or add additional context in comments.

4 Comments

Oh, much nicer. I've never had use for islice before, but this is certainly a perfect case. @user3636424, you might want to accept this answer instead.
@Tim I'm not fussed about accept/reps - just happy it's useful for someone :)
@JonClements: Me neither, but this is the better answer and should be on top.
@Tim well - it appears the OP took your advice... thanks for the edit.
2

Use enumerate():

for i, row in enumerate(datareader):
    MyArray.append(row)
    if i == 10000:
        break

or, for any range:

start = 1000
stop = 2000
for i, row in enumerate(datareader):
    if i < start: 
        continue     # skip this row
    elif i > stop:
        break        # abort the loop
    else:            # ("else" is not strictly necessary here, but more explicit)
        MyArray.append(row)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.