0

new student here so please excuse my ignorance, I have searched a lot and not found a solution to my problem. I am needing to import a CSV file with mixed data types [ int, float, and string], determine the data type, then do maths on the ints and floats.

The problem is that csv reader converts everything to strings ( or they are already strings?). I can try and convert to float, and if it throws an error message I know it is a string, but how would I tell if it is a float, as my program needs to determine between the two?

I am only allowed to import CSV and no others. This is my second first-year python subject, and really not sure how to do this.

Edit, found one answer that seems similar to my problem, but it still returns the wrong answers, ints are usually, but not always, still returned as string type:

 import csv tests = [ # (Type, Test) (int, int), (float, float), ] def getType(value): for typ, test in tests: try: test(value) return typ except ValueError: print 'value error' continue # No match return str file = open('adult.csv') reader = csv.reader(file) filename = 'output.xml' text = open(filename, 'w') text.write('<?xml version="1.0"?>') text.write('<!DOCTYPE summary [') headers = reader.next() for i in headers: print '<name>' print i print '</name>' print '<dataType>' for a in i[1]: print getType[a] #for row in fields: # text = row[2] # print type(text) print '</dataType>' #for value in i: # print type(value) print '<!ELEMENT summary\n\n>' #text.write('<element>') 
2

1 Answer 1

-1

Ok sorry everybody, think i found some code i think will work:

determine the type of a value which is represented as string in python

SHOULD have searched harder, although still not reliably giving the correct type

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.