CSV variable seems to reset

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • marc wyburn

    CSV variable seems to reset

    Hi, I'm using the CSV module to parse a file using

    whitelistCSV_fi le = open("\\pathtoC SV\\whitelist.c sv",'rb')
    whitelistCSV = csv.reader(whit elistCSV_file)
    for uname, dname, nname in whitelistCSV:
    print uname, dname, nname

    The first time I run the for loop the contents of the file is
    displayed. Subsequent attempts to run the for loop I don't get any
    data back and no exception.

    The only way I can get the data is to run whitelistCSV_fi le = open("\
    \pathtoCSV\\whi telist.csv",'rb ') again.

    I'm stumped as to how I can get around this or work out what the
    problem is, I'm assuming that the 'open' command buffers the data
    somewhere and that data is being wiped out by the CSV module but
    surely this shouldn't happen.

    thanks, Marc.
  • Tim Golden

    #2
    Re: CSV variable seems to reset

    marc wyburn wrote:
    Hi, I'm using the CSV module to parse a file using
    >
    whitelistCSV_fi le = open("\\pathtoC SV\\whitelist.c sv",'rb')
    whitelistCSV = csv.reader(whit elistCSV_file)
    for uname, dname, nname in whitelistCSV:
    print uname, dname, nname
    >
    The first time I run the for loop the contents of the file is
    displayed. Subsequent attempts to run the for loop I don't get any
    data back and no exception.
    That's because the csv reader object is an iterator. You're
    consuming it as you run through it. If you want to keep hold
    of the contents to run again (without reinitialising it) then
    pull the data into a list and iterate over that as many times
    as you like:

    data = list (whitelistCSV)
    for uname, dname, nname in data:
    # do stuff

    for uname, dname, nname in data:
    # do stuff again

    TJG

    Comment

    Working...