2

CSV Reader

  • retag add tags

I have been playing with the csv.reader module in reading a column in the following format.

[‘filename1’,
 ‘filename2’,
 ……….. 
]

However, I end up with getting an extra-bracket which I don’t want

[ ( ‘filename1’,
    ‘filename2’, 
   ………….)
]

Just wondering whether you want to suggest me a pythonic way of getting rid of the “ ( “ and “ )”

Don's avatar
51
Don
asked 2012-06-20 06:13:03 -0500
JervisW's avatar
1.3k
JervisW
updated 2012-06-20 06:47:57 -0500
edit flag offensive 0 remove flag close merge delete

Comments

Good question

JervisW's avatar JervisW (2012-06-21 05:22:01 -0500) edit

Can you share a bit more information? csv.reader.next() returns a list of values each row like [col1, col2, col3]. I'm not sure how you're getting [ (col1, col2, col3) ]

chip's avatar chip (2012-06-21 16:26:23 -0500) edit

@chip. If you do something like list(reader) it will create a list of tuples, rather than returning a single row. I suspect that is what is going on here.

JervisW's avatar JervisW (2012-06-26 04:01:54 -0500) edit
add a comment see more comments

1 Answer

1

Your list has a tuple as its first element. To grab the tuple, just you need to get the 0-th element from the list:

>>> data = [(‘filename1’,
...         ‘filename2’, 
...          ...)]
>>> filenames = data[0]
>>> print filenames
(‘filename1’,
 ‘filename2’, 
 ...)

As tuples can't be altered once they have been created, if you want to change the data in the tuple, you will need to convert it to a list first:

>>> filenames = list(filenames)
>>> print filenames
[‘filename1’,
 ‘filename2’, 
 ...]
Daniel_Hillier's avatar
462
Daniel_Hillier
answered 2012-06-26 03:55:44 -0500
edit flag offensive 0 remove flag delete link

Comments

add a comment see more comments

Your Answer

Login/Signup to Answer