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]

user1345260
  • 2,151
  • 12
  • 33
  • 42

1 Answers1

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  
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Can you please explain the initial try command? – user1345260 Feb 03 '14 at 12:39
  • @user1345260: Actually, I was wrong, the [`next()` builtin](http://docs.python.org/2/library/functions.html#next) 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. – Martijn Pieters Feb 03 '14 at 12:42
  • @user1345260: But I removed it, it is redundant here, and your question is really a dupe. – Martijn Pieters Feb 03 '14 at 12:42
  • And shouldn't I remove [:1] from the line for line in reader[:1]: – user1345260 Feb 03 '14 at 12:46
  • Yes. `+++ OUT OF CAFFIENE ERROR +++ REDO FROM START +++` (e.g. my mistake, sorry) – Martijn Pieters Feb 03 '14 at 12:49
  • At the line next(reader, None) it says typeerror dict object is not callable – user1345260 Feb 03 '14 at 12:58
  • @user1345260: Then you already used `next` for a dictionary object in your local code. Use `del next` to get rid of that dictionary, or rename it in your script. – Martijn Pieters Feb 03 '14 at 12:59