質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

CSS

CSSはXMLやHTMLで表現した色・レイアウト・フォントなどの要素を指示する仕様の1つです。

Q&A

解決済

2回答

3993閲覧

python csvのファイルのヘッダーを一回のみ出力したい

August.

総合スコア7

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

CSS

CSSはXMLやHTMLで表現した色・レイアウト・フォントなどの要素を指示する仕様の1つです。

0グッド

0クリップ

投稿2021/08/31 03:02

python

1import serial 2import time 3from datetime import datetime 4import sys 5import csv 6 7# LED display rule. Normal Off. 8DISPLAY_RULE_NORMALLY_OFF = 0 9 10# LED display rule. Normal On. 11DISPLAY_RULE_NORMALLY_ON = 1 12 13def s16(value): 14 return -(value & 0x8000) | (value & 0x7fff) 15 16def calc_crc(buf, length): 17 """ 18 CRC-16 calculation. 19 20 """ 21 crc = 0xFFFF 22 for i in range(length): 23 crc = crc ^ buf[i] 24 for i in range(8): 25 carrayFlag = crc & 1 26 crc = crc >> 1 27 if (carrayFlag == 1): 28 crc = crc ^ 0xA001 29 crcH = crc >> 8 30 crcL = crc & 0x00FF 31 return (bytearray([crcL, crcH])) 32 33 34def print_latest_data(data): 35 """ 36 print measured latest value. 37 """ 38 time_measured = datetime.now().strftime("%Y/%m/%d %H:%M:%S") 39 temperature = str( s16(int(hex(data[9]) + '{:02x}'.format(data[8], 'x'), 16)) / 100) 40 relative_humidity = str(int(hex(data[11]) + '{:02x}'.format(data[10], 'x'), 16) / 100) 41 ambient_light = str(int(hex(data[13]) + '{:02x}'.format(data[12], 'x'), 16)) 42 barometric_pressure = str(int(hex(data[17]) + '{:02x}'.format(data[16], 'x') 43 + '{:02x}'.format(data[15], 'x') + '{:02x}'.format(data[14], 'x'), 16) / 1000) 44 sound_noise = str(int(hex(data[19]) + '{:02x}'.format(data[18], 'x'), 16) / 100) 45 eTVOC = str(int(hex(data[21]) + '{:02x}'.format(data[20], 'x'), 16)) 46 eCO2 = str(int(hex(data[23]) + '{:02x}'.format(data[22], 'x'), 16)) 47 discomfort_index = str(int(hex(data[25]) + '{:02x}'.format(data[24], 'x'), 16) / 100) 48 heat_stroke = str(s16(int(hex(data[27]) + '{:02x}'.format(data[26], 'x'), 16)) / 100) 49 vibration_information = str(int(hex(data[28]), 16)) 50 si_value = str(int(hex(data[30]) + '{:02x}'.format(data[29], 'x'), 16) / 10) 51 pga = str(int(hex(data[32]) + '{:02x}'.format(data[31], 'x'), 16) / 10) 52 seismic_intensity = str(int(hex(data[34]) + '{:02x}'.format(data[33], 'x'), 16) / 1000) 53 temperature_flag = str(int(hex(data[36]) + '{:02x}'.format(data[35], 'x'), 16)) 54 relative_humidity_flag = str(int(hex(data[38]) + '{:02x}'.format(data[37], 'x'), 16)) 55 ambient_light_flag = str(int(hex(data[40]) + '{:02x}'.format(data[39], 'x'), 16)) 56 barometric_pressure_flag = str(int(hex(data[42]) + '{:02x}'.format(data[41], 'x'), 16)) 57 sound_noise_flag = str(int(hex(data[44]) + '{:02x}'.format(data[43], 'x'), 16)) 58 etvoc_flag = str(int(hex(data[46]) + '{:02x}'.format(data[45], 'x'), 16)) 59 eco2_flag = str(int(hex(data[48]) + '{:02x}'.format(data[47], 'x'), 16)) 60 discomfort_index_flag = str(int(hex(data[50]) + '{:02x}'.format(data[49], 'x'), 16)) 61 heat_stroke_flag = str(int(hex(data[52]) + '{:02x}'.format(data[51], 'x'), 16)) 62 si_value_flag = str(int(hex(data[53]), 16)) 63 pga_flag = str(int(hex(data[54]), 16)) 64 seismic_intensity_flag = str(int(hex(data[55]), 16)) 65 print("") 66 print("時間:" + time_measured) 67 print("気温:" + temperature) 68 print("湿度:" + relative_humidity) 69 print("明るさ:" + ambient_light) 70 print("気圧:" + barometric_pressure) 71 print("騒音:" + sound_noise) 72 print("eTVOC:" + eTVOC) 73 print("CO2:" + eCO2) 74 print("不快指数:" + discomfort_index) 75 print("熱中症危険度::" + heat_stroke) 76 print("振動情報:" + vibration_information) 77 print("SI 値:" + si_value) 78 print("加速度:" + pga) 79 print("震度:" + seismic_intensity) 80# print("Temperature flag:" + temperature_flag) 81# print("Relative humidity flag:" + relative_humidity_flag) 82# print("Ambient light flag:" + ambient_light_flag) 83# print("Barometric pressure flag:" + barometric_pressure_flag) 84# print("Sound noise flag:" + sound_noise_flag) 85# print("eTVOC flag:" + etvoc_flag) 86# print("eCO2 flag:" + eco2_flag) 87# print("Discomfort index flag:" + discomfort_index_flag) 88# print("Heat stroke flag:" + heat_stroke_flag) 89# print("SI value flag:" + si_value_flag) 90# print("PGA flag:" + pga_flag) 91# print("Seismic intensity flag:" + seismic_intensity_flag) 92 with open('Book.csv','a',newline='') as f: 93 writer = csv.writer(f) 94 writer.writerow(['時間','気温','湿度','明るさ','気圧']) 95 writer.writerow([time_measured,temperature,relative_humidity,ambient_light,barometric_pressure]) 96 97def now_utc_str(): 98 """ 99 Get now utc. 100 """ 101 return datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") 102 103 104if __name__ == '__main__': 105 106 # Serial. 107 ser = serial.Serial("/dev/ttyUSB0", 115200, serial.EIGHTBITS, serial.PARITY_NONE) 108 109 try: 110 # LED On. Color of Green. 111 command = bytearray([0x52, 0x42, 0x0a, 0x00, 0x02, 0x11, 0x51, DISPLAY_RULE_NORMALLY_ON, 0x00, 0, 255, 0]) 112 command = command + calc_crc(command, len(command)) 113 ser.write(command) 114 time.sleep(0.1) 115 ret = ser.read(ser.inWaiting()) 116 117 while ser.isOpen(): 118 # Get Latest data Long. 119 command = bytearray([0x52, 0x42, 0x05, 0x00, 0x01, 0x21, 0x50]) 120 command = command + calc_crc(command, len(command)) 121 tmp = ser.write(command) 122 time.sleep(0.1) 123 data = ser.read(ser.inWaiting()) 124 print_latest_data(data) 125 time.sleep(1) 126 127 except KeyboardInterrupt: 128 # LED Off. 129 command = bytearray([0x52, 0x42, 0x0a, 0x00, 0x02, 0x11, 0x51, DISPLAY_RULE_NORMALLY_OFF, 0x00, 0, 0, 0]) 130 command = command + calc_crc(command, len(command)) 131 ser.write(command) 132 time.sleep(1) 133 # script finish. 134 sys.exit 135 136

こちらが環境センサ(オムロン)で取得したデータを毎秒ごとに表示しながらcsvファイルにてログを残したいのですが、このままだと時間、気温etc...までもが毎秒表記されてしまいます。理想としては
時間、気温、etc...
〇〇、〇〇、〇〇
〇〇、〇〇、〇〇
〇〇、〇〇、〇〇...
のようにしたいです。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答2

0

ベストアンサー

最初に一回だけやりたいことはループの前にやりましょう。
そしてループの中では繰り返しやりたいことだけをやりましょう。

最初に一回やりたいこと

python

1 with open('Book.csv','a',newline='') as f: 2 writer = csv.writer(f) 3 writer.writerow(['時間','気温','湿度','明るさ','気圧']) 4

繰り返しやりたいこと

python

1 with open('Book.csv','a',newline='') as f: 2 writer = csv.writer(f) 3 writer.writerow([time_measured,temperature,relative_humidity,ambient_light,barometric_pressure]) 4

投稿2021/08/31 03:45

ppaul

総合スコア24666

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

August.

2021/08/31 03:55

ありがとうございます。
guest

0

with open('Book.csv','a',newline='') as f:

のまえに、このファイルが存在してるかどうかをチェックします
存在していないなら、ファイルを作ってヘッダを出力します

あとは、データのみ書き込んでいけばいいです

投稿2021/08/31 03:05

y_waiwai

総合スコア87747

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

August.

2021/08/31 03:55

ありがとうございます。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問