0

I have a piece of code that is writing pressure data to a file. Because the data doesn't have a timestamp, I'm having to add it to the data when I write it to a file. What I'm wondering is if there is a better way to do that in a more elegant way than what I've done so far. Something which combines the f.write() lines into a single line?

clock = time.time()
p = self.pressure()
    
with open('logs.txt', 'a') as f:
    f.write(str(clock))
    f.write(' Pressure: {}\n'.format(p))

The output looks like this:

1609421246.922448 Pressure: 1008.2004978712436
4
  • You could put it all in a small function Commented Dec 31, 2020 at 13:53
  • 2
    Did you try f.write('{} Pressure: {}\n'.format(clock, p))? Commented Dec 31, 2020 at 14:08
  • Thanks Accdias, that looks to have been the magic fix. Commented Dec 31, 2020 at 14:16
  • There is nothing wrong with two writes pre line. With bufferred output (the default), it makes no performance difference either. Commented Dec 31, 2020 at 15:06

1 Answer 1

2

The problem you have can be very easily solved using the logging module in Python.

Here is a simple example for your situation:

"""
Pressure Logging Dummy File.

This a dummy file to provide an example of easily logging pressure data,
with timestamp.
"""
import logging
import random


logging.basicConfig(filename="pressure.log",
                    format='%(asctime)s : %(levelname)s : Pressure : %(message)s',
                    datefmt='%m/%d/%Y %I:%M:%S %p',
                    level=logging.INFO)

pressure_value: int = random.randint(0, 1001)

logging.info("%s", str(pressure_value))

The output of this example (in the file pressure.log) is:

12/31/2020 08:00:59 PM : INFO : Pressure : 850

In your case, if you're only storing sensor readings and not any data about sensor failure or other such debug/warning/error messages, then probably the need for the INFO text is unnecessary (just omit the %(levelname)s).

This will by default append the logs to the file, over multiple runs. It also adds the timestamp automatically when you log new readings. You can also specify the format of the timestamp that you need, just like I have done in the example.

The link I referred to come up with my answer:

  1. https://docs.python.org/3/howto/logging.html
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I'm going to give logging a shot.
Thanks. I'm loving logging and made a few changes to the basicConfig. But I'm going to run with it. --> logging.basicConfig(filename="logs.txt", format='%(created)f : Pressure : %(message)s', level=logging.INFO)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.