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:
- https://docs.python.org/3/howto/logging.html
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…