Python Forum

Full Version: How to put together datas into a file?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I would like to collect different type of datas into a file. Here is a part of the code.
val = str(float(data[-1]))
val_dB = float(val)
val_dB = math.log(val_dB, 10) * 10
myfile = open('../../../MLI_values/mli_value.txt', 'a')
myfile.write(date_ID + " " + val + val_dB + "\n")
myfile.close()

But it gives back an error:
myfile.write(date_ID + " " + val + val_dB + "\n")
TypeError: cannot concatenate 'str' and 'float' objects

How can I solve it to put them ,,together" (into cloumns) into a file?
Well, val_dB is a float. You explicitly made it one on the second line (although given that you made it a float and then made it a string on the previous line, I'm a little confused as to the process). Floats don't add to strings, you need to convert it back to string to do that:

myfile.write(date_ID + " " + val + str(val_dB) + "\n")
Better yet is to use string formatting:

myfile.write('{} {}{}\n'.format(date_ID, val, val_dB)
That will do the conversion for you, and allows for all sorts of ways to format the resulting string. You can see the full format method syntax here.