Python Forum
How to put together datas into a file?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to put together datas into a file?
#1
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?
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  time setup for realtime plotting of serial datas at high sampling rate alice93 6 3,648 Jan-07-2022, 05:41 PM
Last Post: deanhystad
  iterate and print json datas enigma619 1 1,890 Apr-01-2020, 11:48 AM
Last Post: buran
  Datas are not insert into database aravinth 1 2,153 Dec-21-2019, 04:17 PM
Last Post: buran
  Plotting datas Krszt 2 2,346 Oct-31-2018, 03:29 PM
Last Post: Davis4109
  How to put together datas from different files Krszt 3 2,335 Oct-31-2018, 07:37 AM
Last Post: Krszt
  How to write datas into a file? Krszt 2 2,365 Oct-25-2018, 01:45 PM
Last Post: Krszt
  how to retrieve datas with Overpass API python wrapper apollo 0 2,888 Oct-15-2017, 02:27 PM
Last Post: apollo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020