I need to run a python script repeatedly over different data set. This python script test.py processes the data set, plot and save the result using the command.
plt.savefig('result.png')
How can I ensure that when the same test.py
scripts runs on another data set.. the new result.png
doesn't overwrite my previous result? Basically before executing plt.savefig('result.png')
, I need to check if result.png already exist and if does then rename the result to any other name like
result1.png
result2.png
Otherwise, in the next post processing the file is overwritten.
Click the File tab. Click Save As. In the File name box, enter a new name for the file. Click Save.
To overwrite a file, to write new content into a file, we have to open our file in “w” mode, which is the write mode. It will delete the existing content from a file first; then, we can write new content and save it. We have a new file with the name “myFile. txt”.
You can use os.path.exists
to check whether the file already exists, and if so, append a number. Repeat with the new file name until you find one that does not yet exist.
def unique_file(basename, ext):
actualname = "%s.%s" % (basename, ext)
c = itertools.count()
while os.path.exists(actualname):
actualname = "%s (%d).%s" % (basename, next(c), ext)
return actualname
Example-usage:
for i in range(5):
with open(unique_file("foo", "txt"), "w") as f:
f.write(str(i))
import time
if os.path.exists('result.png'):
plt.savefig('result_{}.png'.format(int(time.time())))
else:
plt.savefig('result.png')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With