Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

python - Better way to timestamp a file write

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: {}
'.format(p))

The output looks like this:

1609421246.922448 Pressure: 1008.2004978712436

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...