2

I'm creating an arff file with a lot of numeric data. Now since my feature vector is quite large, I ended up with code like this

with(file,'w') as myfile:
    s = number + ","
    s += number + ","
    s += number + ","
    s += number + ","
    ...
    myfile.write(s)

Since I'm quite new to Python I obviously forgot about the fact that Python doesn't seem to allow floats to be concatenated to strings like that and giving me the following error.

unsupported operand type(s) for +: 'numpy.float64' and 'str'

So how would a more experienced python programmer deal with this problem or do I really have to cast all those numbers to strings like this

with(file,'w') as myfile:
    s = str(number) + ","
    s += str(number) + ","
    s += str(number) + ","
    s += str(number) + ","
    ...
    myfile.write(s)
1
  • 1
    Also for those reading this, I'd like to thank the SO community. Almost all my previous problems where solved by the first link on google, which was a link to SO ^_^ Aug 3, 2014 at 20:47

1 Answer 1

7

Don't write CSV rows by hand. Use the csv module:

with(file, 'wb') as myfile:
    writer = csv.writer(myfile)
    writer.writerow([number1, number2, number3])

Each element in the list is converted to a string for you.

When using numpy arrays, you can use numpy.savetext() to achieve much the same results.

Even without the csv module, you can just a sequence of values into one string with str.join(), with a judicious helping of map() to make sure all values are strings:

s = ','.join(map(str, [number1, number2, number3]))

A quick demo of the latter (using Python 2):

>>> number = 42.4245
>>> string = 'The quick brown fox'
>>> empty = None
>>> map(str, [number, string, empty])
['42.4245', 'The quick brown fox', 'None']
>>> ','.join(map(str, [number, string, empty]))
'42.4245,The quick brown fox,None'

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.