help I'm getting delimited

John Machin sjmachin at lexicon.net
Wed Dec 17 07:44:11 EST 2008


On Dec 17, 9:39 pm, aka <alexoploca... at gmail.com> wrote:
> Due to being in a hurry I didn't paste correctly (sorry).
>
> The intention is to put values of column 1 ("id") in the roles list,
> therefore appending within the loop, to fill a session var.
>
> The complete code is:

It's *not* complete. It's missing "import csv".

>
> roles = []
> inp = 'C:/temp/test.csv'
> try:
>     fp = open(inp, 'rb')
>     reader = csv.reader(fp, dialect='excel', delimiter=';')
>     for r in reader:
>         roles.append(r)
>         ## ultimately should be something like r.id or r[0]
>         ## first row of csv file should be skipped because of column
> names
>
> except:
>     msg = 'Something's wrong with the csv.reader'

But you don't print the message! In any case, using the try/except
like that *hides* any useful diagnostic information; it gives only an
indication that something is wrong, but not what is wrong and where it
is wrong.

If you throw away the try/except, you will get a more meaningful
message -- possibly that "csv" is not defined!! -- and the traceback
will tell you in which line the error occured.

> return dict(file=inp,roles=str(roles))

Why do you think that you need (a) that complicated expression (b) the
str() call? Assuming you are intending to make a function out of all
that, what's wrong with returning a (simple) tuple:
   return inp, roles
?

The above 'return' statement is not inside a function/method. You
would have got this message:
    SyntaxError: 'return' outside function
People will very soon lose patience with you if you persist in not
posting the actual code that you ran.

> The roles list isn't populated at all :(

This could mean (if the code that was posted is moderately similar to
that which was run) that the error happened before the first time that
roles.append(r) was executed ;-)

Please divulge the contents of test.csv  -- but not if it's huge!
Considering trying to get your code to work first with a data file of
close-to-minimal size and complexity, like this:
8<---
id,other_info
tom,1
dick,2
harry,3
8<---

By the way, you mentioned the UnicodeReader class in your original
post, but you don't seem to use it ...



More information about the Python-list mailing list