0

I am reading sensor data and saving in file like this:

with open('serial_data.txt','a') as f:

Problem is, if I write the code five times, it appends in the same file. I want the data of each test in separate file for example if I run code four times, then it should save as: "serial_data_1.txt", "serial_data_2.txt", "serial_data_3.txt", "serial_data_4.txt"..... Is there any way to do this?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Talha Yousuf
  • 301
  • 2
  • 12

3 Answers3

1

I would suggest using CLI parameters

import sys

run = sys.argv[1]
with open('serial_data_{}.txt'.format(run), 'a') as f:

Then do python app.py 1 for the first run

How to read/process command line arguments?

Otherwise, you need to save the number externally, or write a loop in your code that is processing each of your test conditions

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
0

I will suggest you to write à loop in your code as:

for x in range(1, numberOfTest):
    with open("serial_data_{0}.txt".format(x),'a') as f
Manavalan Gajapathy
  • 3,900
  • 2
  • 20
  • 43
Alexandre29
  • 57
  • 2
  • 8
0

If you want to create new files with your data in it you must use the 'w+' tag in your open function as so:

    # Looping and creating multiple files
    for i in range(1, 4):
        # Using 'w+' to create file with such name if
        # it doesn't actually exit
        f = open('serial_data_{}.txt'.format(i), 'w+')
        # Now you can write any data to your file
        f.write('{} squared is {}'.format(i, i*i))
        # Close your file
        f.close()

This will produce 3 files with the following content:

  • serial_data_1 = "1 squared is 1"
  • serial_data_2 = "2 squared is 4"
  • serial_data_3 = "3 squared is 9"

Note: You must close the files after writing. Additionally using 'w+' will overwrite the files every time you run it, use 'a' instead of 'w+' if you want to add/append to the file's current data.

Hopefully that helped :)

aelmosalamy
  • 100
  • 9