csv中无列(csv python模块)

2024-10-02 04:17:10 发布

您现在位置:Python中文网/ 问答频道 /正文

仪器在文件头上创建一个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模块读取这个值。在

^{pr2}$

输出为:

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

很容易获得Xlabel或{}值:

print(row['XLabel'])

但是我怎样才能得到None值呢?在


Tags: 模块文件noneresponse仪器beamcvsfiletype
1条回答
网友
1楼 · 发布于 2024-10-02 04:17:10

只需使用None作为键:

print(row[None])

None只是restkey参数的值,DictReader()None是默认值。你可以把它设置成别的。它是将没有字段名的任何额外列收集到其中的键,在您的示例中,字段名取自文件中只有两个字段的第一行。在

更好的选择是显式地传入一些字段名:

^{pr2}$

因为该格式的第一行并不真正适合作为超过前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)

相关问题 更多 >

    热门问题