1

Im writing a simple command line program involving id's, i want to make it so that every time i run a function it should add a value to a CSV file. I have made a function that i thought worked, but apparently not. One of my for loops is not running correctly ;( Here is my code:

def addId(id):
    file = open(ID_FILE_PATH, 'wb+')
    read = csv.reader(file)
    write = csv.writer(file)

    existingRows = []
    existingRows.append(id)

    for rows in read:  # This does not run
        print rows
        if len(rows) > 0 and rows[0] not in existingRows:
            existingRows.append(rows[0])

    for rows in existingRows: # This runs
        write.writerow([rows])

    file.close()

Sorry for my bad English btw.

2
  • The problem is most probably that you're opening both a csv.reader AND a csv.writer on the same file object. See a similar question here. Commented Jul 8, 2016 at 0:10
  • 1
    Also, you shouldn't name the variable file, as this is a built-in data type Commented Jul 8, 2016 at 0:11

1 Answer 1

2

You open the file with:

file = open(ID_FILE_PATH, 'wb+')

According to the documentation:

note that 'w+' truncates the file

You truncate the file, so no wonder there is nothing to read in! Use rb+ instead.

Sign up to request clarification or add additional context in comments.

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.