1

The following code work fine.

with open(filename, 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
        cur.execute(insertStatement, row)

when I insert these two lines, something goes wrong.

with open(filename, 'rb') as f:
    reader = csv.reader(f)
    totalrows = len(list(reader))
    print totalrows # Print out the correct output
    for row in reader:
        cur.execute(insertStatement, row)   

My guess is that when i assign totalrows = len(list(reader)) the cursor moves to the end of the file there for nothing happens in the for loop.

if this is true how can i move the cursor back to the start without closing the file and reopening it? if not please help.

0

3 Answers 3

4

That's right, the file has been consumed and subsequent reads on reader will not return data.

You can get around this by calling f.seek(0) on the underlying file, i.e.

with open(filename, 'rb') as f:
    reader = csv.reader(f)
    totalrows = len(list(reader))
    print totalrows # Print out the correct output
    f.seek(0)
    for row in reader:
        cur.execute(insertStatement, row)
Sign up to request clarification or add additional context in comments.

1 Comment

@M.ofCA : Blair makes an important point about not reading the file twice in this answer
1

Rather than reading it once, creating and throwing away a list, and reading it again, why don't you keep the list and iterate over that?

with open(filename, 'rb') as f:
    reader = csv.reader(f)
    allrows = list(reader)
    totalrows = len(allrows)
    print totalrows # Print out the correct output
    for row in allrows:
        cur.execute(insertStatement, row)   

Also, many database libraries allow you to insert multiple records at once which is often quicker than inserting them one at a time. Check the documentation for whatever database library you are using.

Comments

0

If that is whats happening, try using f.seek(0) that puts the cursor back to the beginning.

with open(filename, 'rb') as f:
reader = csv.reader(f)
totalrows = len(list(reader))
print totalrows # Print out the correct output
f.seek(0)  # Moves pointer back to beginning of file
for row in reader:
    cur.execute(insertStatement, 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.