我有这段代码用于从Picotech的TC-08温度记录器读取温度并将温度写入CSV文件。问题是温度在文件中以四位小数存储,两位小数甚至一小数对我来说都足够了。
我尝试使用np.around(temp,2)和np.set_printoptions(precision = 2),但它们都没有改变写入CSV文件的小数位数。你能帮助我并告诉我正确的方法吗?
csv_delimiter='\t'
file = 'test.csv'
no_of_channels=6 #set number of channels to read
tc_type=ord('K') #set type of element
no_of_meas = 10
time_interval= 10 #read every 10 sec
#Setup TC08
mydll = ctypes.windll.LoadLibrary('usbtc08.dll')
device = mydll.usb_tc08_open_unit()
mydll.usb_tc08_set_mains(device,50) #set the mains rejection to 50 or 60 Hz
temp = np.zeros( (9,), dtype=np.float32)
overflow_flags = np.zeros( (1,), dtype=np.int16)
mydll.usb_tc08_set_channel(device, 0, 0 )
no_of_channels +=1 #Don't want to read channel 0
for i in range(1,no_of_channels):
mydll.usb_tc08_set_channel(device,i,tc_type)
cur_meas = 1
with open(file, 'a', newline='') as fp:
while cur_meas <= no_of_meas:
timeBegin = time.time()
cur_time = datetime.datetime.strftime(datetime.datetime.now(), '%H:%M:%S')
a = csv.writer(fp, delimiter=csv_delimiter)
mydll.usb_tc08_get_single(device, temp.ctypes.data, overflow_flags.ctypes.data, 0)
#np.around(temp,2)#I have tried this in order to get two decimals
#np.set_printoptions(precision=2)#I have tried this in order to get two decimals
print(temp)
listtemp = temp[1:no_of_channels]
print(listtemp)
data = [[cur_time]+list(listtemp)]
a.writerows(data)
fp.flush()
os .fsync(fp.fileno())
print(', '.join(map(str, data)))
cur_meas += 1
timeEnd = time.time()
timeElapsed = timeEnd - timeBegin
time.sleep(time_interval-timeElapsed)
mydll.usb_tc08_close_unit(device)
答案 0 :(得分:0)
说明显而易见,csv是文本,因此导入时显示的精度可能因每个单元格而异。 圆函数不保证两个小数精度,但格式化浮点数。
f1 = 100.0001
f2 = 99.2345
f3 = 88.7455
f4 = 1.4589
lf1 = [f1, f2, f3, f4]
for f in lf1:
print f
print str(round(f, 2))
print '{0:0.2f}'.format(f) # rounds and formats to two decimal precision
100.0001
100.0
100.00
99.2345
99.23
99.23
88.7455
88.75
88.75
1.4589
1.46
1.46