简体   繁体   English

Python 2.7以.csv格式导出数据

[英]Python 2.7 exporting data in a .csv

I have this piece of code that works at gathering data from a serial port connected machine, the data is then reordered. 我有这段代码用于从串口连接的机器收集数据,然后重新排序数据。 I can successfully print my data at the end : print pigment_data 我可以在最后成功打印我的数据: print pigment_data

However I don't get how to export this data to a .csv file. 但是,我不知道如何将此数据导出.csv文件。

Is there any straightforward way to do this? 有没有直接的方法来做到这一点?

Thank you very much, 非常感谢你,

Adrien 阿德里安

import serial  # requires pyserial library
import csv

ser  = serial.Serial(0)
data = []

while True:
    name = raw_input("Pigment name [DONE to finish]: ")
    if name == "DONE":
        break

    pigment_data = []
    first = True
    main_spect = []

    while True:
        line = ser.readline()
        if first:
            print "  Data incoming..."
            first = False
        split = line.split()
        if 10 <= len(split):
            try:
                wavelength = int(split[0])
                measurements = [float(split[i]) for i in [2,4,6,8,10]]
                pigment_data.append({"wavelength": wavelength,
                                     "measurements": measurements})
                main_spect.append(measurements[2])
            except ValueError:
                pass    # handles the table heading
        if line[:3] == "110":
            break
    data.append({"name": name,
                 "data": pigment_data})
    print "  Data gathered."
    print pigment_data

    # here's the problem:
    with open('spectral_data.csv', 'wb') as f:
        writer = csv.writer(f)
        writer.writerows(pigment_data)

You gathered a list of dictionaries, use csv.DictWriter() here instead to make this easier: 你收集了一个字典列表,在这里使用csv.DictWriter()来改善它:

with open('spectral_data.csv', 'ab') as f:
    writer = csv.DictWriter(f, ('name', 'data'))
    writer.writerow(data[-1])

This opens the file in append-mode as well, since you are opening the file once every loop. 这也会以append-mode打开文件,因为每次循环都会打开一次文件。 I used data[-1] here because that's the last entry you added in the loop. 我在这里使用了data[-1] ,因为这是你在循环中添加的最后一个条目。

You probably want to move the creation of the writer object out of your loop: 您可能希望将writer对象的创建移出循环:

with open('spectral_data.csv', 'wb') as f:
    writer = csv.DictWriter(f, ('name', 'data'))

    while True:
        name = raw_input("Pigment name [DONE to finish]: ")
        # ....

        print pigment_data

        writer.writerow(data[-1])

which writes the newest entry you gathered to the CSV file as you gather it. 它会在您收集CSV文件时将您收集的最新条目写入。

Last but not least, you can also write the whole data list in one go after the outer while True: is done: 最后但并非最不重要的是,您还可以在外部后一次写入整个data列表, while True:完成:

data = []

while True:
    name = raw_input("Pigment name [DONE to finish]: ")
    # ....

with open('spectral_data.csv', 'ab') as f:
    writer = csv.DictWriter(f, ('name', 'data'))
    writer.writerows(data)

from csv.writer 's help: 来自csv.writer的帮助:

writer(...)
    csv_writer = csv.writer(fileobj [, dialect='excel']
                                [optional keyword args])
        for row in sequence:
            csv_writer.writerow(row)

        [or]

        csv_writer = csv.writer(fileobj [, dialect='excel']
                                [optional keyword args])
        csv_writer.writerows(rows)

    The "fileobj" argument can be any object that supports the file API.

so basically you want: 所以基本上你想要:

with open('spectral_data.csv', 'wb') as f:
    writer = csv.writer(f)
    for row in pigment_data:
        writer.writerow(row)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM