0

This may seem like an odd thing to do, but I essentially have a csv file that has some values of '0' in quite a number of cells.

How would I, in Python, convert these numbers to read as something like 0.00 instead of just 0? I have a script in ArcMap which needs to read the values as double rather than short integer, and the '0' value really messes that up.

I am new with the CSV module, so I am not sure where to go with this. Any help with making a script convert my values so that when I open the new CSV, it will read a "0.00" rather than '0' would be greatly appreciated.

I would have liked to have some code to give you as an example, but I am at a loss.

2 Answers 2

1

Here's a short script that will read a CSV file, convert any numbers to floats and then write it back to the same file again.

import csv
import sys

# These indices won't be converted
dont_touch = [0]
def convert(index, value):
    if not index in dont_touch:
         try:
              return float(value)
         except ValueError:
              # Not parseable as a number
              pass
    return value

table = []
with open(sys.argv[1]) as f:
    for row in csv.reader(f, delimiter=","):
        for i in range(len(row)):
            row[i] = convert(i, row[i])
                table.append(row)

with open(sys.argv[1], "w") as f:
    writer = csv.writer(f, delimiter=",")
        writer.writerows(table)

If you have any columns that should not be converted, specify their indices in the dont_touch array.

If you want them to have two trailing zeroes you can play around with format strings instead:

return "{:.02f}".format(float(value))
Sign up to request clarification or add additional context in comments.

Comments

0

You can format the 0s and then write them out, you may want to look into the appropriate quoting for your csv (e.g. you may need quoting=csv.QUOTE_NONE in your writer object):

reader = csv.reader(fr)
writer = csv.writer(fw)
for row in reader:
    writer.writerow([f if f != '0' else '{:0.2f}'.format(0) for f in row])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.