[英]Python writing floats into csv
I am writing some data into a csv with Python. 我正在使用Python将一些数据写入csv。 I have two values, downloadSpeed
and uploadSpeed
. 我有两个值, downloadSpeed
和uploadSpeed
。 When the value of the data is < 1 it is written into the csv file properly ( 0.58795654 becames 0.58795654 ). 当数据的值<1时,它将被正确地写入csv文件( 0.58795654 变为0.58795654 )。 However, when the data is >1, float value is converted into an integer ( 2.58795654 becames 258795654 ). 但是,当数据> 1时,浮点值将转换为整数( 2.58795654 变为258795654 )。 This is my code: 这是我的代码:
with open(data_file_path, 'a+', newline='') as csvfile:
file = csv.writer(csvfile, delimiter=';')
file.writerow([date,downloadSpeed, uploadSpeed])
One solution I have come up with is converting the float to String, and then writing the string replacing the '.' 我想出的一种解决方案是将float转换为String,然后编写字符串以替换'。'。 for ','. 为“,”。 However, after some reading, I don´t know why was this happening. 但是,经过一番阅读,我不知道为什么会这样。
Solution: 解:
file.writerow([date, str(downloadSpeed).replace(".",","), str(uploadSpeed).replace(".",",")])
Edit: 编辑:
The problem is that Excel accepts both ,
and .
问题是,Excel的同时接受,
和.
as separators for floats < 1 but only accepts ,
as separator for floats > 1. That is why I was getting the error. 作为浮点数<1的分隔符,但仅接受,
作为浮点数> 1的分隔符。这就是为什么我得到这个错误。
This seems to be working 这似乎正在工作
import csv
import datetime
date = datetime.datetime.now()
downloadSpeed = 2.58795654
uploadSpeed = 0.2261624210544645
with open("test.csv", "a+", newline='') as file:
writer = csv.writer(file, delimiter=';')
writer.writerow([date,downloadSpeed, uploadSpeed])
Output is: 2018-05-02 15:58:38.294086;2.58795654;0.2261624210544645 输出是:2018-05-02 15:58:38.294086; 2.58795654; 0.2261624210544645
Are you altering the numbers in some way before writing? 您是否在写之前以某种方式更改了数字?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.