Python通过不带括号字符的文件导出到文件

2024-04-26 14:25:38 发布

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

我成功地简化了从光谱仪导入数据的python模块 (我完全是个初学者,别人为我写了代码的模型……)

我只有一个问题:一半的输出数据(在.csv文件中)被方括号包围:[]

我希望文件包含如下结构:

name, wavelength, measurement

a,400,0.34
a,410,0.65
...

但我得到的是:

a,400,[0.34]
a,410,[0.65]
...

有什么简单的解决办法吗?你知道吗

是因为measurementstring?你知道吗

谢谢

import serial  # requires pyserial library

ser  = serial.Serial(0)
ofile = file( 'spectral_data.csv', 'ab')

while True:
    name = raw_input("Pigment name [Q to finish]: ")
    if name == "Q":
        print "bye bye!"
        ofile.close()
        break

    first = True

    while True:
        line = ser.readline()
        if first:
            print "  Data incoming..."
            first = False
        split = line.split()
        if 10 <= len(split):
            try:
                wavelength = int(split[0])
                measurement = [float(split[i]) for i in [6]]
                ofile.write(str(name) + "," + str(wavelength) + "," + str(measurement) + '\n')

            except ValueError:
                pass    # handles the table heading
        if line[:3] == "110":
            break

    print "  Data gathered."
    ofile.write('\n')

Tags: 文件csv数据nametrueiflineserial
1条回答
网友
1楼 · 发布于 2024-04-26 14:25:38

请执行以下操作:

measurement = [float(split[i]) for i in [6]]
ofile.write(str(name) + "," + str(wavelength) + "," + ",".join(measurement) + '\n')

ofile.write(str(name) + "," + str(wavelength) + "," + split[6] + '\n')

相关问题 更多 >