How to log and save file with date and timestamp in Python
<p>I am trying to log temperature from a DS18B20 sensor using Raspberry Pi 3 via Python code executed from shell.</p>

<p>I want to log temperature with timestamp and then save the file.</p>

<p>What I am doing presently is saving it to a filename entered in the code, but I want to log the file with date and timestamp in filename.</p>

<p><strong>Case 1 :</strong> When I put a filename in the code, then I can append data to the same file over and over, but I can't start a new separate logging without editing the code.</p>

<pre><code>#Writes data to file
def write_temp(temperature):
        with open("/home/pi/temp.csv", "a") as log:
                log.write("{0},{1}\n".format(strftime("%Y-%m-%d %H:%M:%S"),str(temperature)))
</code></pre>

<p>Problem is that the file is always temp.csv and data gets appended each time.</p>

<p><strong>Case 2</strong>: I tried to get filename from timestamp, but each second a new file is getting generated.</p>

<pre><code>def write_temp(temperature):
        filename1 = strftime("%Y-%m-%d %H:%M:%S")
        #filename1 = sys.argv[1]
        with open('%s.csv' % filename1, 'a') as log:
                log.write("{0},{1}\n".format(strftime("%Y-%m-%d %H:%M:%S"),str(temperature)))
</code></pre>

<p>In the above case, I would rather like to have the filename set at the start of logging each time or at the end of logging. I would also like to save the name as Log-<em>DateTime</em> instead of just DateTime. I tried this by doing <code>('"Log-" + %s.csv' % filename1, 'a')</code> instead of <code>('%s.csv' % filename1, 'a')</code>, but that didn't work out.</p>

<p><strong>Ideal Case:</strong> I want file name to be WORD-<em>DateTime</em>, where WORD is sent as an argument from the command line, as in below:</p>

<pre><code>sudo python TTLogging.py WORD
</code></pre>

<p>Can you point out where I am going wrong? I can share the full code of my work if required since it is a learning exercise.</p>

<p>Try :</p>

<pre><code>with open('Log-%s.csv' % filename1, 'a') as log:
</code></pre>

python csv datetime raspberry-pi