0
lines = node_record.splitlines()
reader = csv.reader(lines, delimiter=',')
rows = []
node_id_pos = -1
        
for i, row in enumerate(reader):
           
   if len(row) == 2:
       return rows
   if i == 0:
    try:         
       node_id_pos = row.index('nid')
       row[row.index('_start')] = 'start'
       row[row.index('_end')] = 'end'
       row[row.index('_type')] = 'type'
    except:
       raise ValueError('Invalid row: {} {}'.format(str(row), row['_id']))

In the code above, when an exception occurs, it print outs the literal string:

raise ValueError('Invalid row: {} {}'.format(str(row), row['_id']))
TypeError: list indices must be integers or slices, not str

Why the row's values are not printed out?

marlon
  • 6,029
  • 8
  • 42
  • 76
  • You are getting a `TypeError` while trying to format the text for `ValueError`. Check `row['_id']`. – Selcuk Nov 09 '21 at 04:01
  • you cannot do this in list `row['_id']`, see on the TypeError log. If you want use string to call row value, use dictionary instead – Rizquuula Nov 09 '21 at 04:01
  • I think you meant `row[row.index('_id')]`, but you should be using dictionaries. – enzo Nov 09 '21 at 04:03
  • What's confusing about that error message? The only indexing in the mentioned line is `row['_id']`, and `row` is a list. – wjandrea Nov 09 '21 at 04:10
  • 1
    BTW, [a bare `except` is bad practice](/q/54948548/4518341). Instead, use the specific exception(s) you're expecting like `except ValueError`, or at least `except Exception`. – wjandrea Nov 09 '21 at 04:11
  • Did you mean to use [`csv.DictReader`](https://docs.python.org/3/library/csv.html#csv.DictReader) instead of `csv.reader`? – wjandrea Nov 09 '21 at 04:16

1 Answers1

0

The error occurs because you are trying to retrieve data from a list by a string: row['_id'].

Maybe this is what you want:

raise ValueError('Invalid row: {} {}'.format(str(row), row[row.index('_id')]))