I have a CSV file containing numbers in the fields,
I write a script, trying to take square root of numbers in every field in this CSV file,
import sys, os
import csv, math
import tempfile
import shutil
element = []
filename = 'test.csv'
with open(filename, 'rb') as f, tempfile.NamedTemporaryFile(mode='wb', delete=False) as g:
writer = csv.writer(g, delimiter = ',')
for row in csv.reader(f):
element = element in row
row = math.sqrt(element)
writer.writerow([row])
shutil.move(g.name, filename)
But the output is not what I want,
What should I edit my script?
You are calculating square root of False, which is the same as square root of 0
>>> element = element in row
False
>>> row = math.sqrt(element)
0
Modify it like this:
filename = 'test.csv'
with open(filename, 'rb') as f, tempfile.NamedTemporaryFile(mode='wb', delete=False) as g:
writer = csv.writer(g, delimiter = ',')
for row in csv.reader(f):
row = [math.sqrt(float(num)) for num in row]
writer.writerow(row)