0

So I'm writing a little script in python to read the temperature of built-in core sensor(Raspberry Pi) + print it on the screen + write the data to the .txt file. Everything is working pretty much, but I have two problems which I couldn't solve and I have spent like 3-4 hours on it. Fully output of that command is for example: temp=39.0'C and I need only the number from that string --> 39.0. So I'm trying to replace characters and part of the string that I don't need and make it number float.

return temp.replace("temp=", " ").replace("'C", "") My problem is when I'm running this code I still have 1 space before my number and that's because I'm replacing "temp=" with " ", but if I delete that space second replace becomes part of the string and it doesn't do its job anymore, in my opinion, there's too many --> """""'""" of those characters and program gets confused. But how can I solve it? Second problem how can I change it to float because, in my opinion, those numbers are still part of the string? Please help because I am so frustrated that such little script takes so much time to get it working.

import re
import os
import time

def measure_temp():

temp = os.popen("vcgencmd measure_temp").readline()
return temp.replace("temp=", " ").replace("'C", "")

while True:

temperature = measure_temp()
print(temperature)

f = open("pythonLog.txt", "a")
f.write (temperature)
f.close()

time.sleep(1)
Marcus
  • 401
  • 6
  • 13
  • 1
    To prevent all the string mangling, just read `/sys/class/thermal/thermal_zone0/temp`, convert to float and divide by 1000. – Klaus D. Nov 24 '20 at 08:35
  • can you help me change that code a bit cause ive no clue how to do it :( – Arturas Zavialovas Nov 24 '20 at 08:41
  • As google reveals you not wrote the code on your own, but copied it from a website. Stack Overflow is not the right place to get copied code adapted to your needs. We assist people who are programming which included learning the language. – Klaus D. Nov 24 '20 at 08:44
  • [Here](https://stackoverflow.com/questions/4703390/how-to-extract-a-floating-number-from-a-string) is an SO answer about extracting a float from a string. I.e. it may be easier to extract the number from the string than it is to remove everything except the number – adamkgray Nov 24 '20 at 08:47
  • @KlausD. thats not true i didnt just copy paste it, yesterday i was working about 4 hours on thats code. And yes i looked up online for some examples and maybe took line from one site and other line from other site. But thats how im learning. Thats my forst time working with python + Rpi. how else can i learn if i cant look for anything online. – Arturas Zavialovas Nov 24 '20 at 08:51

1 Answers1

0

Thanks to all who trie to help i have solved by extracting by using temp = temp[1] so the space at the index 0 is gone.