我有这段代码用于从串口连接的机器收集数据,然后重新排序数据。
我可以在最后成功打印我的数据:print pigment_data
但是,我不知道如何将此数据导出到.csv
文件。
有没有直截了当的方法呢?
非常感谢,
阿德里安
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)
答案 0 :(得分:3)
您收集了一个词典列表,请在此处使用csv.DictWriter()
,以便更轻松:
with open('spectral_data.csv', 'ab') as f:
writer = csv.DictWriter(f, ('name', 'data'))
writer.writerow(data[-1])
这也会以append-mode打开文件,因为每个循环都会打开一次文件。我在这里使用了data[-1]
,因为这是你在循环中添加的最后一个条目。
您可能希望移动循环的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])
将您收集的最新条目写入CSV文件。
最后但并非最不重要的是,您也可以在外部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)
答案 1 :(得分:0)
来自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.
所以基本上你想要:
with open('spectral_data.csv', 'wb') as f:
writer = csv.writer(f)
for row in pigment_data:
writer.writerow(row)