1

I'm new to Raspberry so I need a bit of help. I have a DS18B20 temperature sensor, which I want to write the measurements into a file. I have a script running, making measurement printing to screen every second, at the same time it updates the text file with the last measurement, but I would like to have all the measurements in the text file.

I'm using this script:

print(read_temp())

dataAsInt = (read_temp())

    dataAsString = str(dataAsInt)

    fb = open("/home/pi/test2","a" '\n')
    fb.write(dataAsString) 
    fb.close()

I've tryed using "a" for appending instead of writing and '\n' for writing on next line.

Hope someone can point me the right direction.

3
  • Hello and welcome! Please note that the question is not Pi specific (and therefore off-topic) but only related to python as a general programming language.
    – Ghanima
    Commented Dec 8, 2015 at 9:10
  • Thanks, so I should have posted in what group instead?
    – Thomas
    Commented Dec 8, 2015 at 9:43
  • Technically that would be Stack Overflow. But lets try to sort this one out here. If it's closed afterwards, well than that's that.
    – Ghanima
    Commented Dec 8, 2015 at 9:55

1 Answer 1

2

fb = open('/home/pi/test2','a+')

should do the trick. It opens the file in appending mode for read and write access. Placing the '\n' there is not what you want. Instead simply explicitly append a '\n' each time you want a line break, e.g. fb.write('\n'). For the given example that would look like:

dataAsInt = (read_temp())
dataAsString = str(dataAsInt)

fb = open('/home/pi/test2','a+')
fb.write(dataAsString) 
fb.write('\n')
fb.close()

Note that open() states (i.e. there will be a line break, maybe your text editor just does not treat it right):

The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading.

3
  • Adding the 'a+' fixed the problem with adding all measurements. But I can't get the \n to work.
    – Thomas
    Commented Dec 8, 2015 at 9:43
  • If you put fb.write('\n') after fb.write(dataAsString) (on the next line) that does not add a line break? It should.
    – Ghanima
    Commented Dec 8, 2015 at 9:52
  • I misunderstood you the first time. It fixes the problem, i'm now logging my temperature in the text file with new line for every measurement. Thanks a lot
    – Thomas
    Commented Dec 8, 2015 at 9:54

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.