csv中没有列(csv python模块)

时间:2016-07-18 20:33:21

标签: python csv

仪器在文件头上创建一个CVS:

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

我想用cvs python模块读取这个值。

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)

输出结果为:

{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'}

很容易获得XlabelWavenumber值:

print(row['XLabel'])

但我怎样才能获得None值?

1 个答案:

答案 0 :(得分:2)

只需使用None作为密钥:

print(row[None])

None只是restkey DictReader()参数的值,None是默认值。您可以将其设置为其他内容。它是收集任何没有字段名的额外列的密钥,在您的情况下,字段名取自文件的第一行,该行只有两个字段。< / p>

更好的选择是明确传入一些字段名:

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

因为该格式的第一行不适合作为前5行之后的列的标签。您可以选择对这4列有意义的名称。

请注意,您必须跳过 5 行,而不是4.请参阅Python CSV reader to skip 9 headers了解您无需保留计数器的替代技术:

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)