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?

1

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you ! I was trying row['None'] :x
@FrancoisDion: Added some more explanation as to what is going on, and a better alternative.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.