0

Having troubles when creating a txt.file for everytime I run my python code. The code is supposed to collect data for quite some time, but whenever I name the txt.file by the current time in hours and minutes (ex. 12:00), the script will create a new file whenever the clock hits the next minute (ex. 12:01) while the code is running. Anyway of stopping this from happening?

Code:

import sys

sys.path.append('../../')
import time
import datetime

from DFRobot_BMX160 import BMX160

bmx = BMX160(1)

while not bmx.begin():
    time.sleep(2)

def main():

    while True:
        data= bmx.get_all_data()
        moment = time.strftime("%d-%m-%Y",time.localtime())
        file = open('IMU ' + moment + '.txt', "a")
        file.write(datetime.datetime.now().strftime("%d-%m-%Y  %H:%M:%S.%f")[:-3] + "  ")
        file.write("magnetometer  {0:.2f} uT  {1:.2f} uT  {2:.2f} uT".format(data[0],data[1],data[2]) + "\n")
        file.write(datetime.datetime.now().strftime("%d-%m-%Y  %H:%M:%S.%f")[:-3] + "  ")
        file.write("gyroscope  {0:.2f} g  {1:.2f} g  {2:.2f} g".format(data[3],data[4],data[5]) + "\n")
        file.write(datetime.datetime.now().strftime("%d-%m-%Y  %H:%M:%S.%f")[:-3] + "  ")
        file.write("accelerometer  {0:.2f} m/s^2  {1:.2f} m/s^2  {2:.2f} m/s^2".format(data[6],data[7],data[8]) + "\n")
        
         
if __name__ == "__main__":
    main()
slowmoocow
  • 49
  • 5
  • 2
    Please clarify what you mean by "The code is supposed to collect data for quite some time, but whenever I name the txt.file by the current time in hours and minutes (ex. 12:00), the script will create a new file whenever the clock hits the next minute (ex. 12:01) while the code is running. " What is it you want to happen and what is actually happening? – itprorh66 Apr 26 '22 at 23:08
  • Also, read [this article](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) to debug your code to understand what it is actually doing. – Code-Apprentice Apr 26 '22 at 23:12
  • Side note: be careful about global variables. It is best practice to only define functions and classes at the top level. You can move the 4 lines above `def main()` into the `main()` function to avoid this. – Code-Apprentice Apr 26 '22 at 23:14
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – lpounng Apr 27 '22 at 03:22

1 Answers1

1

This seems to be because you redefine moment every time the code loops within your infinite while loop.

file = open('IMU ' + moment + '.txt', "a") will create a new file anytime the file you name doesn't exist, and since moment is the current time, this will happen whenever the clock strikes a new minute.

To avoid this, consider either defining moment outside of the while loop, if you would like to log only one file when running the code, or to use if conditions to set when you would like a new file to be made.

Also, since you open but never close your files, if you run this script for long enough, there might be issues with many open files. It's best practice to explicitly close files when you are done with them (see here: Is close() necessary when using iterator on a Python file object). And since you don't have an explicit exit condition in your loop, you might want to add a break condition or something similar that will close your log file, in case of a crash or you keyboard interrupting the program, as it's the best way to ensure you reliably save your data.