6

When I try to open a file in python I get the error, typeerror '_csv.reader' object is not subscriptable. The code is as below, can someone kindly help me please

with open(file) as f:  
    reader = csv.reader(f, delimiter='\t')  
    for line in reader:  
        oldseq, city, state, newseq = line  

The error is here, in the following code, for line in reader[:1]:

with open(newfile) as f:  
    reader = csv.reader(f, delimiter='\t')  
    for line in reader[:1]:  
        oldseq, city, state, newseq = line  

I need to just skip the first line as it has headers, thats why I was doing reader[:1]

5
  • If you show us the full traceback, we most likely can help you find where the real problem is occurring. It is not in the code you posted. Commented Feb 3, 2014 at 12:17
  • I just updated the code & now Im pointing to the error, can you please help Commented Feb 3, 2014 at 12:23
  • You are trying to skip the header of the CSV file. Slicing doesn't work, use reader.next() instead to skip the first row. Commented Feb 3, 2014 at 12:27
  • How about reader(next) would that work? Commented Feb 3, 2014 at 12:28
  • Oops, I see now that next() was added in 2.6 already. Commented Feb 3, 2014 at 12:41

1 Answer 1

5

You cannot slice a reader object; you can skip the first row with:

with open(newfile) as f:  
    reader = csv.reader(f, delimiter='\t')
    next(reader, None)  # skip header
    for line in reader:  
        oldseq, city, state, newseq = line  
Sign up to request clarification or add additional context in comments.

7 Comments

Can you please explain the initial try command?
@user1345260: Actually, I was wrong, the next() builtin was added in 2.6 already. The try tests if the name exists, in Python 2.5 trying to access next will rase a NameError and the except block then defines a Python-only implementation that does the same thing as the built-in.
@user1345260: But I removed it, it is redundant here, and your question is really a dupe.
And shouldn't I remove [:1] from the line for line in reader[:1]:
Yes. +++ OUT OF CAFFIENE ERROR +++ REDO FROM START +++ (e.g. my mistake, sorry)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.