我正在使用Python代码创建CSV文件。 我能够创建和存储数据。但是我无法在csv文件中添加标题,即列名。 我创建了数据框。 用于创建和附加csv的代码如下:
main_app.py:
def handle_data(data):
msg5 = data.replace("\n"," ").replace("\r"," ").split(",")
print(msg5)
d = dict(s.split(':') for s in msg5)
data_frame = pd.DataFrame(list(d.items())).transpose()
data_frame.columns = data_frame.iloc[0]
data_frame = data_frame.reindex(data_frame.index.drop(0))
print(data_frame)
filename = (value_text + time2 + ".csv")
#print(filename)
fields = list(data_frame.columns)
with open(filename, 'a',newline='') as writeFile:
writeFile = csv.writer(writeFile)
writeFile.writerow(fields)
writeFile.writerows(data_frame.values)
def read_from_port(ser):
while True:
reading = ser.readline()
handle_data(reading.decode("utf-8"))```
read_from_port(serial_port)
此代码在每次迭代时都会添加列名称:
我得到的输出:
A B C
0 0 0
A B C
1 1 1
.......
我需要的输出是:
A B C
0 0 0
1 1 1
2 2 2
.....
有人可以帮助我吗? 预先感谢。
答案 0 :(得分:0)
csv.DictWriter可以为您做到这一点!
csvfile = csv.DictWriter(writeFile, fieldnames=fields)
csvfile.writeheader()
csvfile.writerows(data_frame.values)