manxing
manxing

Reputation: 3325

how to set accuracy when using csv writer in python

I have a float variable, obj["time"], which represents the unix time, previously I write the result to a text file, so I could use

  fd_out.write("%.6f\n" %(obj["time"])) 

to force the result to have 6 decimal. But now I want to print the result into csv file instead, so I used:

  writer.writerow((obj["time"]))

the result only have 2 decimal by default, how could I change it?

Upvotes: 2

Views: 3960

Answers (3)

Mark Ransom
Mark Ransom

Reputation: 308432

When you were writing directly to the file, you did a formatting operation to convert the float variable to a string with the desired number of digits. You can do the exact same thing for the CSV writer.

writer.writerow("%.6f" %(obj["time"]))

As pointed out in the comments you'll need to leave out the newline, since the CSV writer will add that for you.

Upvotes: 1

Otto Allmendinger
Otto Allmendinger

Reputation: 28278

Using an intermediate format should solve your problem, like this example:

writer.writerow(("%.6f" % obj["time"], ))

Upvotes: 3

Andre Blum
Andre Blum

Reputation: 391

from the earlier answer at Specifying formatting for csv.writer in Python:

class TypedWriter:
    """
    A CSV writer which will write rows to CSV file "f",
    which uses "fieldformats" to format fields.
    """

    def __init__(self, f, fieldnames, fieldformats, **kwds):
        self.writer = csv.DictWriter(f, fieldnames, **kwds)
        self.formats = fieldformats

    def writerow(self, row):
        self.writer.writerow(dict((k, self.formats[k] % v) 
                                  for k, v in row.iteritems()))

    def writerows(self, rows):
        for row in rows:
            self.writerow(row)

Upvotes: 1

Related Questions