0

An instrument create a CVS with this on the file header :

XLabel,Wavenumber
YLabel,Response
FileType,Single Beam
DisplayDirection,20300
PeakDirection,20312
0.000000,-1.149420,-1.177183,-1.174535
0.964406,-1.053002,-1.083787,-1.069919
1.928811,-0.629619,-0.652436,-0.628358

I want to read this value with cvs python module.

import csv
expfile='test.csv'
with open(expfile) as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        if (i<4):
            i += 1
        else:
            print(row)

The output is :

{None: ['-1.025449', '-1.049773'], 'XLabel': '0.000000', 'Wavenumber': '-1.012466'}
{None: ['-1.256103', '-1.297049'], 'XLabel': '0.964406', 'Wavenumber': '-1.254550'}
{None: ['-0.722499', '-0.754096'], 'XLabel': '1.928811', 'Wavenumber': '-0.735748'}

It is easy to get Xlabel or Wavenumber value :

print(row['XLabel'])

But how can I get the None value?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • See [Python CSV reader to skip 9 headers](https://stackoverflow.com/q/28603014) for a better way to skip a certain number of rows in a CSV file. – Martijn Pieters Jul 18 '16 at 20:35

1 Answers1

2

Just use None as the key:

print(row[None])

None is simply the value for the restkey argument to DictReader(), and None is the default. You could set it to something else. It is the key into which any extra columns that don't have a fieldname are collected into, and in your case the fieldnames are taken from the first row in the file, which has only two fields.

A better option would be to explicitly pass in some fieldnames:

reader = csv.DictReader(csvfile, fieldnames=('Field1', 'Field2', 'Field3', 'Field4'))

because the first row of that format is not really suitable to act as labels for the columns past the first 5 rows. You can pick names that make sense for those 4 columns.

Note you'd have to skip 5 rows then, not 4. See Python CSV reader to skip 9 headers for an alternative technique where you don't have to keep a counter:

from itertools import islice
import csv

expfile='test.csv'

with open(expfile) as csvfile:
    reader = csv.DictReader(csvfile, fieldnames=('Field1', 'Field2', 'Field3', 'Field4'))
    next(islice(reader, 5, 5), None)
    for row in reader:
        print(row)
Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Thank you ! I was trying row['None'] :x – Francois Dion Jul 18 '16 at 20:38
  • @FrancoisDion: Added some more explanation as to what is going on, and a better alternative. – Martijn Pieters Jul 18 '16 at 20:40
  • In case someone is confused by his linter warning him about `Unexpected type` when using `row[None]`, the issue is known and [has been recently fixed](https://github.com/python/typeshed/commit/5e907afac729787b414050d318daeb5a1c59d6a5). – Jeyekomon Jul 19 '21 at 16:45