Jahat120 - 8 months ago 53

Python Question

Hi I'm trying to create multiple samples from a signal. To do this, when the fft is drawn i'm also outputting the frequency and the amplitude to a csv file. The problem with this though is that I'm only making one sample because the output file just gets overwritten every time. What I want to do is check if the file 'output.csv' exists already, and if so append incrementing numbers for each new file along the lines of 'output1.csv' 'output2.csv' and so on. Any help would be greatly appreciated

`def draw_fft(self):`

self.plot_fft[0].set_data([self.freq, self.iq_fft])

self.sp_fft.set_xlim(self.freq.min(), self.freq.max())

self.sp_fft.set_ylim([self.iq_fft.min()-10, self.iq_fft.max()+10])

# for debugging print(self.freq,self.iq_fft)

freqOut = np.array(self.freq)

amplOut = np.array(self.iq_fft)

output = np.column_stack((freqOut.flatten(),amplOut.flatten())

# where the file check should occur

np.savetxt('output.csv',output,delimiter=',')

Answer Source

Sure you could do that. How about instead appending something more informative to the filename e.g. the date and time at the moment.

This way you don't have to check for the presence of a file.

```
import datetime as dt
def draw_fft(self):
...
outputfilename = 'output_{}.csv'.format( dt.datetime.now().strftime('%Y%m%d%H%M%S') )
np.savetxt(outputfilename, output, delimiter=',')
```