peets
peets

Reputation: 441

python csv writes too many decimals

A well discussed problem, but could not find a suitable answer. writing a float list of points (n,3) of 3D vectors to a file using code:

...
with open(filename,"w") as f:
    csvw=csv.writer(f,delimiter=";",quotechar='"')
    for point in points:
        csvw.writerow(point)

gives file content:

 0.04471017781221634;0.0;0.999
-0.05707349435937544;-0.052283996037127314;0.997
 0.008731637417420734;0.09949250478307754;0.995
 0.0718653614139638;-0.09373563798705578;0.993
 ...

for a million points this is a waste of memory. Using binary coding is not easy to transfer to other programs. So I would prefer a more compact format like :

 0.044;0.0;0.999
-0.057;-0.052;0.997
 0.008;0.099;0.995
 0.071;-0.093;0.993
 ...

Here decimals are cut off, rounding is preferred. How can I change or extend the code? Thanks in advance.

Upvotes: 1

Views: 63

Answers (1)

Sidiox
Sidiox

Reputation: 91

[See also][1]

Python has a built in [round][2], which allows you to specify the number of digits via a second argument. So your code would become, assuming each point is indeed just a list of your dimensions like [0.04471017781221634,0.0,0.999]

with open(filename,"w") as f:
    for point in points:
        rounded_point = [round(dim, 3) for dim in point]
        csvw.writerow(rounded_point)

The key point is the rounded_point = [round(dim, 3) for dim in point], which is a list comprehension, where the round function gets applied to each dim in the list of point.
[1]: Limiting floats to two decimal points
[2]: https://docs.python.org/3/library/functions.html#round

Upvotes: 3

Related Questions